java - HttpPost 中的 org.apache.http.client.ClientProtocolException

标签 java android http-post

我尝试将一些字符串上传到服务器。当我尝试在服务器上上传时,以字符串形式:

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

最佳答案

这应该有效

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

}

关于java - HttpPost 中的 org.apache.http.client.ClientProtocolException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15549637/

相关文章:

http - golang http.Post 请求返回响应 404

java - 将 JVisualVM 连接到远程 Wildfly 实例?

java - 将 1 位小数的 double 转换为 2 位小数

javascript - Ajax 的数据和 fetch API 的主体有什么区别?

android - 如何获取当前主题操作栏背景颜色?

android - Beta by Crashlytics 应用程序未安装

json - golang json 解码,请求体为空

Java 转换、覆盖和多态性

java - 为什么 IndexOutOfBoundsException 现在在 Java 16 中有一个带有长索引作为参数的构造函数?

java - 如何使用 Java 代码启动 Tomcat 服务器?