Android HTTP Response Handling

2019-09-03 03:10发布

here's my code that sends an HTTP Request :

package com.example.database;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class post extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    postData();
}


public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost("http://192.168.83.1/test.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        ResponseHandler<String> responseHandler=new BasicResponseHandler();

        String responseBody = httpclient.execute(httppost, responseHandler);
        Log.d("test", responseBody); 
       // Toast.makeText(getApplicationContext(), responseBody, Toast.LENGTH_LONG).show();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

The contents of the file test.php are :

 <?php

echo"works";

?>

the Log.d("test", responseBody); tag doesn't appear onto LogCat.However , if I shift it up a few lines (before responseBody) and put a static piece of text , it does work

Is there a problem with the HTTPRequest ? How could it be solved

Thanks !

1条回答
贪生不怕死
2楼-- · 2019-09-03 04:06

try after removing BasicResponseHandler. it should work. and check in Menifest for perticuler permission

HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity()); 
查看更多
登录 后发表回答