简体   繁体   中英

POST using HttpPost in an android not returning JSON string, returns error

So I am trying to post to this api: http://www.idmypill.com/api/id/ in my android program. This is my service handler class:

public class ServiceHandler 
{ 
  static String response = null;
  public final static int GET = 1;
  public final static int POST = 2;

  public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method, 
        List<NameValuePair> params) 
{
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        android.os.Debug.waitForDebugger();
        // Checking http request method type
        if (method == POST) 
        {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-type", "application/json");
            // adding post params
            if (params != null) 
            {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

}

The response I am getting is: Response:(1990): > {"errors": null, "results": [], "success": false}

My main activity that is calling my service handler looks like:

public class QueryAPI extends Activity 
{
  private ProgressDialog pDialog;

  // URL to get contacts JSON
  private static String url = "http://www.idmypill.com/api/id/api";

  Bitmap pillPicture; 

  List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);


  public void onCreate(Bundle savedInstanceState) 
  {
      super.onCreate(savedInstanceState);
      Intent QueryAPI = getIntent();
      pillPicture = (Bitmap) QueryAPI.getParcelableExtra("PillImage"); 
      nameValuePair.add(new BasicNameValuePair("api_key",      "AIzaSyAdxxOjmh_nx4dKP_uJhtKy3cr32jrs7C8"));
      nameValuePair.add(new BasicNameValuePair("image", "pillPicture"));

      new GetPillInfo().execute(); 
  }


private class GetPillInfo extends AsyncTask<Void, Void, Void>
{

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(QueryAPI.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) 
    {
        android.os.Debug.waitForDebugger();
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST, nameValuePair);

        Log.d("Response: ", "> " + jsonStr);

          if (jsonStr != null)
          {
              try 
              {
                  JSONObject jsonObj = new JSONObject(jsonStr);


                  Log.d("JSON", jsonObj.toString()); 



              } catch (JSONException e) {
                  e.printStackTrace();
              }
          } else 
          {
              Log.e("ServiceHandler", "Couldn't get any data from the url");
          }

          return null;
      }

      @Override
      protected void onPostExecute(Void result)
      {
          super.onPostExecute(result);
          // Dismiss the progress dialog
          if (pDialog.isShowing())
              pDialog.dismiss();
      }
  }
}

The python example the website gives look like this:

# highly suggested to use the requests package
# http://www.python-requests.org/en/latest/
import requests

# read in the image and construct the payload
image = open("example.jpg").read()
data = {"api_key": "KH8hdoai0wrjB0LyeA3EMu5n4icwyOQo"}
files = {"image": open("example.jpg")}

# fire off the request
r = requests.post("http://www.idmypill.com/api/id/", 
data = data, 
files = files)

# contents will be returned as a JSON string
print r.content

I am not familiar with Python and very new to using Http request so an advice would be great.

The api wants a MultiPartEntity containing a text value with key api_key and a image file with key image .

Android does not natively support MultiPart Uploads but you can archive it with Apache's HTTP Library which is actually an updated version of Android's HTTP Library since they are the same thing.

Once you have the library installed, which is simply adding the dependency in gradle then modify your code for something similar:

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("api_key", yourAPIKey);
    builder.addBinaryBody("image", inputStream); // Flexible here, see below
    httpPost.setEntity(builder.build());
    httpResponse = httpClient.execute(httpPost);

The .addBinaryBody() actually has various ways of receiving the image, you can either pass a File a InputStream or the full byte[] array of the image.

You are not returning any result.The return method was Void.That's why you were unable to see any result in Log.

Change your AsyncTask to

private class GetPillInfo extends AsyncTask {

@Override
protected void onPreExecute()
{
    super.onPreExecute();
    // Showing progress dialog
    pDialog = new ProgressDialog(QueryAPI.this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.show();

}

@Override
protected String doInBackground(String... arg0) 
{
    android.os.Debug.waitForDebugger();
    // Creating service handler class instance
    ServiceHandler sh = new ServiceHandler();

    // Making a request to url and getting response
    String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST, nameValuePair);

    Log.d("Response: ", "> " + jsonStr);

      if (jsonStr != null)
      {
          try 
          {
              JSONObject jsonObj = new JSONObject(jsonStr);


              Log.d("JSON", jsonObj.toString()); 



          } catch (JSONException e) {
              e.printStackTrace();
          }
      } else 
      {
          Log.e("ServiceHandler", "Couldn't get any data from the url");
      }

      return null;
  }

  @Override
  protected void onPostExecute(String result)
  {
      super.onPostExecute(result);
      // Dismiss the progress dialog
      if (pDialog.isShowing())
          pDialog.dismiss();
  }

} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM