简体   繁体   中英

org.apache.http.client.ClientProtocolException in HttpPost

I try upload some string to server. When I try upload on server, in string:

        HttpResponse response = httpclient.execute(httppost);

I have error org.apache.http.client.ClientProtocolException. All code:

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

This should work

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

}

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