0

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

我正在使用的功能是这样的:

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

}

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

...

4

2 回答 2

0

如果响应是字符串类型,试试这个

  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;
于 2012-12-17T06:30:05.533 回答
0

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

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

...因为那是说“扔掉内容”。

于 2012-12-17T04:36:26.153 回答