WebService - POST |
Top Previous Next |
Web using System;
namespace GetPost { public partial class pagina : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Page.EnableViewState = false; if (Request.QueryString["codigo"] != null) { string[] lista = new string[5] { "Jessica", "Angelina", "Natalie", "Charlize", "Scarlet" }; int codigo = int.Parse(Request.QueryString["codigo"].ToString()); string retorno = (codigo < 1 || codigo > 5) ? "ERR: Código inválido" : lista[codigo - 1];
Response.Clear(); Response.Expires = -1; // Requerido para manter a pagina no cache do navegador Response.ContentType = "text/plain"; Response.Write(retorno); Response.End(); } } } }
Para testar, basta publicá-la (no meu caso em http://help.market.com.br/pagina.aspx) e testar com um parâmetro: http://help.market.com.br/pagina.aspx?codigo=5
retorno:
App Android - Completo - conexão normal e via JAKARTA
Todos os fontes abaixo Tela
Http.java
package com.webservice;
import java.util.Map;
public abstract class Http { //utiliza UrlConnection public static final int NORMAL = 1; //Utiliza o Jakarta HttpClient public static final int JAKARTA = 2; public static Http getInstance(int tipo){ switch (tipo) { case NORMAL: //UrlConnection return new HttpNormalImpl(); case JAKARTA: //Jakarta Commons HttpClient return new HttpClientImpl(); default: return new HttpNormalImpl(); } } //retorna o texto do arquivo public abstract String downloadArquivo(String url); //retorna os bytes da imagem public abstract byte[] downloadImagem(String url); //faz post enviando os parâmetros public abstract String doPost(String url, Map<String, Integer> map); }
HttpClientImpl.Java
package com.webservice;
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map;
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP;
import android.util.Log;
public class HttpClientImpl extends Http { private final String CATEGORIA = "livro";
@Override public final String downloadArquivo(String url) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url);
Log.i(CATEGORIA, "request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget);
Log.i(CATEGORIA, "----------------------------------------"); Log.i(CATEGORIA, String.valueOf(response.getStatusLine())); Log.i(CATEGORIA, "----------------------------------------");
HttpEntity entity = response.getEntity();
if (entity != null) { Log.i(CATEGORIA, "Lendo resposta"); InputStream in = entity.getContent(); String texto = readString(in); return texto; } } catch (Exception e) { Log.e(CATEGORIA, e.getMessage(), e); } return null; }
@Override public final byte[] downloadImagem(String url) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url);
Log.i(CATEGORIA, "request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
Log.i(CATEGORIA, "----------------------------------------"); Log.i(CATEGORIA, String.valueOf(response.getStatusLine())); Log.i(CATEGORIA, "----------------------------------------");
HttpEntity entity = response.getEntity();
if (entity != null) { Log.i(CATEGORIA, "Lendo resposta..."); InputStream in = entity.getContent(); byte[] bytes = readBytes(in); Log.i(CATEGORIA, "Resposta: " + bytes); return bytes; } } catch (Exception e) { Log.e(CATEGORIA, e.getMessage(), e); } return null; }
@Override public final String doPost(String url, Map<String, Integer> map) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url);
Log.i(CATEGORIA, "HttpClient.post " + httpPost.getURI());
// cria os parâmetros List<NameValuePair> params = getParams(map); // seta os parametros para enviar httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
Log.i(CATEGORIA, "HttpClient.params " + params);
HttpResponse response = httpclient.execute(httpPost);
Log.i(CATEGORIA, "----------------------------------------"); Log.i(CATEGORIA, String.valueOf(response.getStatusLine())); Log.i(CATEGORIA, "----------------------------------------");
HttpEntity entity = response.getEntity();
if (entity != null) { InputStream in = entity.getContent(); String texto = readString(in); Log.i(CATEGORIA, "Resposta: " + texto); return texto; } } catch (Exception e) { Log.e(CATEGORIA, e.getMessage(), e); } return null; }
private byte[] readBytes(InputStream in) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { bos.write(buf, 0, len); }
byte[] bytes = bos.toByteArray(); return bytes; } finally { bos.close(); } }
private String readString(InputStream in) throws IOException { byte[] bytes = readBytes(in); String texto = new String(bytes); return texto; }
private List<NameValuePair> getParams(Map<String, Integer> map) throws IOException { if (map == null || map.size() == 0) { return null; }
List<NameValuePair> params = new ArrayList<NameValuePair>();
Iterator<String> e = (Iterator<String>) map.keySet().iterator(); while (e.hasNext()) { String name = (String) e.next(); Object value = map.get(name); params.add(new BasicNameValuePair(name, String.valueOf(value))); }
return params; } }
HttpNormalImpl.java
package com.webservice;
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Map;
import android.util.Log;
public class HttpNormalImpl extends Http {
private final String CATEGORIA = "livro";
@Override public final String downloadArquivo(String url) { Log.i(CATEGORIA, "Http.downloadArquivo: " + url); try { // Cria a URL URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection();
// Configura a requisição para get // connection.setRequestProperty("Request-Method","GET"); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(false); conn.connect();
InputStream in = conn.getInputStream();
// String arquivo = readBufferedString(sb, in); String arquivo = readString(in);
conn.disconnect();
return arquivo; } catch (MalformedURLException e) { Log.e(CATEGORIA, e.getMessage(), e); } catch (IOException e) { Log.e(CATEGORIA, e.getMessage(), e); } return null; }
@Override public final byte[] downloadImagem(String url) { Log.i(CATEGORIA, "Http.downloadImagem: " + url); try { // Cria a URL URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection(); // Configura a requisição para get connection.setRequestProperty("Request-Method", "GET"); connection.setDoInput(true); connection.setDoOutput(false);
connection.connect();
InputStream in = connection.getInputStream();
// String arquivo = readBufferedString(sb, in); byte[] bytes = readBytes(in);
Log.i(CATEGORIA, "imagem retornada com: " + bytes.length + " bytes");
connection.disconnect();
return bytes;
} catch (MalformedURLException e) { Log.e(CATEGORIA, e.getMessage(), e); } catch (IOException e) { Log.e(CATEGORIA, e.getMessage(), e); } return null; }
@Override public String doPost(String url, Map<String, Integer> params) { try { String queryString = getQueryString(params); String texto = doPost(url, queryString); return texto; } catch (IOException e) { Log.e(CATEGORIA, e.getMessage(), e); } return url; }
// Faz um requsição POST na URL informada e retorna o texto // Os parâmetros são enviados ao servidor private String doPost(String url, String params) throws IOException { Log.i(CATEGORIA, "Http.doPost: " + url + "?" + params); URL u = new URL(url + "?" + params);
HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true);
conn.connect();
OutputStream out = conn.getOutputStream(); byte[] bytes = params.getBytes("UTF8"); out.write(bytes); out.flush(); out.close();
InputStream in = conn.getInputStream();
// le o texto String texto = readString(in);
conn.disconnect();
return texto; }
// Transforma o HashMap em uma query string fazer o POST private String getQueryString(Map<String, Integer> params) throws IOException { if (params == null || params.size() == 0) { return null; } String urlParams = null; Iterator<String> e = (Iterator<String>) params.keySet().iterator(); while (e.hasNext()) { String chave = (String) e.next(); Object objValor = params.get(chave); String valor = objValor.toString(); urlParams = urlParams == null ? "" : urlParams + "&"; urlParams += chave + "=" + valor; } return urlParams; }
// Faz a leitura do array de bytes da InputStream retornada private byte[] readBytes(InputStream in) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { bos.write(buffer, 0, len); } byte[] bytes = bos.toByteArray(); return bytes; } finally { bos.close(); in.close(); } }
// Faz a leitura do texto da InputStream retornada private String readString(InputStream in) throws IOException { byte[] bytes = readBytes(in); String texto = new String(bytes); Log.i(CATEGORIA, "Http.readString: " + texto); return texto; } }
TesteWebServiceActivity.java
package com.webservice;
import java.util.HashMap; import java.util.Map;
import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;
public class TesteWebServiceActivity extends Activity implements OnClickListener, Runnable {
// componentes visuais TextView tvResposta; Button btConsultar; EditText edCodigo;
// handler usado para atualizar a view private Handler handler = new Handler(); private ProgressDialog dialog;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
AssociarComponentes(); }
private void AssociarComponentes() { tvResposta = (TextView) findViewById(R.id.tvResposta); edCodigo = (EditText) findViewById(R.id.edCodigo); btConsultar = (Button) findViewById(R.id.btConsultar); btConsultar.setOnClickListener(this); }
public void onClick(View v) { dialog = ProgressDialog.show(this, "Exemplo", "Buscando texto, aguarde...", false, true); // faz o download numa thread new Thread(this).start(); }
public void run() {
try { int codigo = Integer.parseInt(edCodigo.getText().toString());
final String url = "http://www.help.market.com.br/pagina.aspx";
Map<String, Integer> params = new HashMap<String, Integer>(); params.put("codigo", codigo); final String resultado = Http.getInstance(Http.NORMAL).doPost(url, params);
try {
// precisa do handler para atualizar a view de outra thread handler.post(new Runnable() {
public void run() { tvResposta.setText(resultado); } });
} catch (Exception e) { e.printStackTrace(); }
} catch (Throwable e) { Log.e("Erro", e.getMessage(), e); } finally { dialog.dismiss(); } } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Digite o código" />
<EditText android:id="@+id/edCodigo" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="number" >
<requestFocus /> </EditText>
<Button android:id="@+id/btConsultar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Consultar" />
<TextView android:id="@+id/tvResposta" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Resposta" />
</LinearLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.webservice" android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".TesteWebServiceActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
</manifest>
Projeto
|