Java Android HttpPost:如何获取结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2323617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android HttpPost: how to get the result
提问by Sumit M Asok
I have been trying long to send an HttpPost request and retrieve response but even though I was able to make a connection I don't yet get how to get the string message which is returned by the request-response
我一直在尝试发送 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();
}
I'm sorry, I sound very naive because I'm new to java. Please help me.
对不起,我听起来很幼稚,因为我是 Java 新手。请帮我。
采纳答案by Moritz
Try to use the EntityUtil
on your response:
尝试EntityUtil
在您的回复中使用 :
String responseBody = EntityUtils.toString(response.getEntity());
回答by Sumit M Asok
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();
}
This code snippet works. I got it after along search , but from a J2ME code.
此代码片段有效。我在 search 之后得到了它,但是来自 J2ME 代码。
回答by Sarp Centel
You can call execute method with a ResponseHandler. Here's an example:
您可以使用 ResponseHandler 调用 execute 方法。下面是一个例子:
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httppost, responseHandler);
回答by SamB
Try this, it seems to be the most compact. Although in the real world, you'd need to use an asynchronous request so the device won't hang while the requested page is being retrieved.
试试这个,好像是最紧凑的。尽管在现实世界中,您需要使用异步请求,以便在检索请求的页面时设备不会挂起。
http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/
http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/
回答by Siddhpura Amit
You can do this by this way :
你可以通过这种方式做到这一点:
public class MyHttpPostProjectActivity extends Activity implements OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendPostReqButton;
private Button clearButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
usernameEditText = (EditText) findViewById(R.id.login_username_editText);
passwordEditText = (EditText) findViewById(R.id.login_password_editText);
sendPostReqButton = (Button) findViewById(R.id.login_sendPostReq_button);
sendPostReqButton.setOnClickListener(this);
clearButton = (Button) findViewById(R.id.login_clear_button);
clearButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.login_clear_button){
usernameEditText.setText("");
passwordEditText.setText("");
passwordEditText.setCursorVisible(false);
passwordEditText.setFocusable(false);
usernameEditText.setCursorVisible(true);
passwordEditText.setFocusable(true);
}else if(v.getId() == R.id.login_sendPostReq_button){
String givenUsername = usernameEditText.getEditableText().toString();
String givenPassword = passwordEditText.getEditableText().toString();
System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);
sendPostRequest(givenUsername, givenPassword);
}
}
private void sendPostRequest(String givenUsername, String givenPassword) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
// In a POST request, we don't pass the values in the URL.
//Therefore we use only the web page URL as the parameter of the HttpPost argument
HttpPost httpPost = new HttpPost("http://www.nirmana.lk/hec/android/postLogin.php");
// Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
//uniquely separate by the other end.
//To achieve that we use BasicNameValuePair
//Things we need to pass with the POST request
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);
// We add the content that we want to pass with the POST request to as name-value pairs
//Now we put those sending details to an ArrayList with type safe of NameValuePair
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
try {
// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
//This is typically useful while sending an HTTP POST request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("working")){
Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
}
回答by Hélène
You should try using HttpGet instead of HttpPost. I had a similar problem and that solved it.
您应该尝试使用 HttpGet 而不是 HttpPost。我有一个类似的问题,并解决了它。