2013-03-21 78 views
1

我嘗試上傳一些字符串到服務器。當我嘗試上載服務器,在字符串:org.apache.http.client.ClientProtocolException在HttpPost

 HttpResponse response = httpclient.execute(httppost); 

我有錯誤org.apache.http.client.ClientProtocolException。所有代碼:

public void sendString(String stringToSend) { 

    try { 
     DefaultHttpClient httpclient = new DefaultHttpClient(); 
     httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); 
     HttpPost httppost = new HttpPost(serverAddress); 
     InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(stringToSend.getBytes()), stringToSend.length()); 
     reqEntity.setContentType("application/xml"); 
     httppost.setEntity(reqEntity); 
     HttpResponse response = httpclient.execute(httppost); 
     if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) { 
      Log.i("SEND", "not send "+response.getStatusLine()); 
     }else{ 
      Log.i("SEND", "send ok "+response.getStatusLine()); 
     } 
    } catch (IOException e) { 
     Log.w("IOException", e.toString() +" "+ e.getMessage()); 
    }   
} 
+0

索裏我找到了答案。如果有人會有這個錯誤,我這樣修復它: StringEntity se = new StringEntity(stringToSend,HTTP.UTF_8); se.setContentType(「text/xml」);httppost.setEntity(se); – Dima 2013-03-21 14:59:09

回答

0

這應該工作

public void sendString(String stringToSend) { 

try { 
    HttpParams httpParams=new BasicHttpParams(); 
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParams); 
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); 
    HttpPost httppost = new HttpPost(serverAddress); 
    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(stringToSend.getBytes()), stringToSend.length()); 
    reqEntity.setContentType("application/xml"); 
    httppost.setEntity(reqEntity); 
    HttpResponse response = httpclient.execute(httppost); 
    if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) { 
     Log.i("SEND", "not send "+response.getStatusLine()); 
    }else{ 
     Log.i("SEND", "send ok "+response.getStatusLine()); 
    } 
} catch (IOException e) { 
    Log.w("IOException", e.toString() +" "+ e.getMessage()); 
}   

}

+0

在我的情況下,我有一些空白或空值的標題。刪除它們解決了我的問題 – Alex 2015-06-17 12:32:09