我的Android应用程序中有一个使用HttpPost类的方法。 它有针对性的sdk 4.4.2正常工作,但我做了一些改动,使目标sdk达到23(6.0)。 现在HttpPost类给出了错误。 我也读过关于HttpUrlConnection但还不知道如何使用它。 这是我的代码
private String getJSON(String URL, JSONObject obj) throws JSONException {
String responseString = null;
try {
HttpPost httppost = new HttpPost(URL);
StringEntity se = new StringEntity(obj.toString(), HTTP.UTF_8);
httppost.setHeader("Content-Type", "application/json");
httppost.setEntity(se);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpResponse httpResponse = httpclient.execute(httppost);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println("status code is" + statusCode);
HttpEntity entity = httpResponse.getEntity();
responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println("response string" + responseString);
Log.i("RESPONSE XML ------> ", "-----> " + responseString);
return responseString;
} catch (Exception e) {
e.printStackTrace();
}
return responseString;
}
请帮助我做什么,或者如果可能的话,提供此功能的课程将适用于23。 提前致谢
答案 0 :(得分:1)
使用 HttpUrlConnection
将代码中的代码替换为下面给出的代码import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
public class TestJava {
private String getJSON(String URL, JSONObject obj) throws JSONException {
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(URL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(30000);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.write(obj.toString().getBytes("UTF-8"));
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}