我正在尝试通过发出HTTP请求更新Android中的MySQL数据,但它给了我一个错误
“类型不匹配:无法从org.apache.http.HttpResponse转换为com.google.api.client.http.HttpResponse”
在这行代码“httpClient.execute(httpPost)”
上HttpResponse response = httpClient.execute(httpPost);
它通过添加org.apache.http等提供快速修复的选项和选项
org.apache.http.HttpResponse response = httpClient.execute(httpPost);
有人可以告诉我这里我做错了什么吗?非常感谢你!
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://---.com/---/approve_request.php");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("status", "Approved"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
org.apache.http.HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
答案 0 :(得分:5)
您的代码中的import语句错误。
转到课堂顶部并寻找
import com.google.api.client.http.HttpResponse
替换为
import org.apache.http.HttpResponse
答案 1 :(得分:2)
使用import org.apache.http.HttpResponse;
而不是import com.google.api.client.http.HttpResponse;
答案 2 :(得分:1)
你会有
import com.google.api.client.http.HttpResponse;
在源代码顶部的导入列表中。
请将其更新至
import org.apache.http.HttpResponse;.
httpClient.execute(httpPost);
正在返回org.apache.http.HttpResponse
个对象,并且导入类型不正确,您试图将其转换为com.google.api.client.http.HttpResponse
,这会导致问题。
答案 3 :(得分:1)
org.apache.http.HttpResponse
和com.google.api.client.http.HttpResponse
是两个完全独立且不同的Java类。你不能只是简单地拿一个并将其转换为另一个。如果您使用的是Apache HttpClient
,那么它将始终返回org.apache.http.HttpResponse
,而不是Android版本。如果你确实想使用Apache的HttpClient,那么我建议你坚持使用Apache版本而不是Android版本的HttpResponse,并根据需要直接提取标题/内容。
答案 4 :(得分:1)
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("status", "Approved"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
""http://---.com/---/approve_request.php"");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}