Sum*_*sok 50 java android http
我一直在尝试发送HttpPost请求并检索响应,但即使我能够建立连接,我还没有得到如何获取请求 - 响应返回的字符串消息
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php");
// Add your data
List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > (5);
nameValuePairs.add(new BasicNameValuePair("type", "20"));
nameValuePairs.add(new BasicNameValuePair("mob", "919895865899"));
nameValuePairs.add(new BasicNameValuePair("pack", "0"));
nameValuePairs.add(new BasicNameValuePair("exchk", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("myapp", "works till here. 2");
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("myapp", "response " + response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
对不起,我听起来很天真,因为我是java的新手.请帮我.
Mor*_*itz 99
尝试使用EntityUtil您的回复:
String responseBody = EntityUtils.toString(response.getEntity());
Run Code Online (Sandbox Code Playgroud)
URL url;
url = new URL("http://www.url.com/app.php");
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httppost = (HttpURLConnection) connection;
httppost.setDoInput(true);
httppost.setDoOutput(true);
httppost.setRequestMethod("POST");
httppost.setRequestProperty("User-Agent", "Tranz-Version-t1.914");
httppost.setRequestProperty("Accept_Language", "en-US");
httppost.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
DataOutputStream dos = new DataOutputStream(httppost.getOutputStream());
dos.write(b); // bytes[] b of post data
String reply;
InputStream in = httppost.getInputStream();
StringBuffer sb = new StringBuffer();
try {
int chr;
while ((chr = in.read()) != -1) {
sb.append((char) chr);
}
reply = sb.toString();
} finally {
in.close();
}
Run Code Online (Sandbox Code Playgroud)
此代码段有效.我在搜索之后得到了它,但是来自J2ME代码.
您可以使用ResponseHandler调用execute方法.这是一个例子:
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httppost, responseHandler);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88733 次 |
| 最近记录: |