获取HttpResponse的Web服务响应

时间:2012-12-17 03:47:41

标签: java android web-services httpresponse image-uploading

在我的应用程序中,用户可以将图像上传到PHP服务器,iOS版本100%工作,用于本教程的Android版本上传图像: tutorial example

我正在使用的功能就是:

public static String sendPost(String url, String imagePath) 
        throws IOException, ClientProtocolException  {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                                        HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost(url);
    File file = new File(imagePath);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);

    httppost.setEntity(mpEntity);
    //Log.e("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    //Log.e(""+response.getStatusLine());
    if (resEntity != null) {
        //Log.e(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
    return response.toString();

}
  

return response.toString();在org.apache.http.message.BasicHttpResponse @ 406dc148

中获取

但是Web服务的返回是保存图像的URL,我需要在PHP服务器的返回中有一个字符串,而不是上面提到的返回我怎么能拥有它?

我想要这样的东西(HttpURLConnection): HttpURLConnection conn; ...

String response= "";
Scanner inStream = new Scanner(conn.getInputStream());

while(inStream.hasNextLine())
    response+=(inStream.nextLine());
Log.e("resp", response);

一小时后,onsegui尝试从Web服务获取响应,如下所示: ...

byte [] responseBody = httppost.getMethod().getBytes(); 
Log.e("RESPONSE BODY",""+(new String(responseBody)));

...

2 个答案:

答案 0 :(得分:0)

如果您想要HTTP服务器返回的内容,则不应该这样做:

if (resEntity != null) {
    resEntity.consumeContent();
}

...因为这说“扔掉了内容”。

答案 1 :(得分:0)

如果响应的类型为String

,请尝试此操作
  ResponseHandler<String> responseHandler = new BasicResponseHandler();
  HttpResponse httpResponse = httpClient.execute(post, new BasicHttpContext()); // new BasicHttpContext() not necessary 
// verify connection response status using httpResponse.getStatusLine().getStatusCode() then

  String response =  responseHandler.handleResponse(httpResponse);
  if(response != mull){
     Log.e("Response : "+response);
  }else{
   // Handle exception 
  }
 return response;