在没有返回JSON字符串的android中使用HttpPost进行POST,返回错误

时间:2014-10-17 05:04:46

标签: java android python json http-post

所以我想在我的android程序中发布这个api:http://www.idmypill.com/api/id/。这是我的service处理程序类:

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;

}

}

我得到的回应是:Response:(1990): > {"errors": null, "results": [], "success": false}

我调用服务处理程序的主要活动如下:

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();
      }
  }
}

网站给出的python示例如下:

# 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

我不熟悉Python并且对使用Http请求非常新,所以建议会很棒。

2 个答案:

答案 0 :(得分:1)

api想要一个MultiPartEntity,其中text值为api_key,而file图片为image

Android本身并不支持MultiPart上传,但您可以使用Apache's HTTP Library对其进行存档,这实际上是Android的HTTP库的更新版本,因为它们是相同的。

一旦安装了库,只需在gradle中添加依赖项,然后修改代码以获得类似的代码:

    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);

.addBinaryBody()实际上有各种方式接收图片,您可以传递File InputStream或图片的完整byte[]数组。

答案 1 :(得分:0)

你没有返回任何结果。返回方法是Void。这就是你无法在Log中看到任何结果的原因。

将AsyncTask更改为

私有类GetPillInfo扩展了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();
  }

} }