在Android API 22之前,我只是执行以下操作:
/**
*
* @param url
* @param params
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public InputStream getStreamFromConnection(String url, List<NameValuePair> params) throws ClientProtocolException, IOException {
if(ConnectionDetector.isConnectedToInternet(this.context)) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity.getContent();
} else {
return null;
}
}
现在,上述代码中几乎所有内容都已弃用(NameValuePair
,DefaultHttpClient
,HttpPost
,UrlEncodedFormEntity
,HttpResponse
,HttpEntity
,{ {1}})我无法在API 22+中找到推荐的方法。我现在该怎么办?
答案 0 :(得分:5)
您现在可以使用HttpURLConnection,您可以在以下链接中找到完整的说明:
http://developer.android.com/reference/java/net/HttpURLConnection.html
答案 1 :(得分:5)
这是使用POST方法执行异步任务的示例:
private class SendMessageTask extends AsyncTask<String, Void, String> {
Graduate targetGraduate;
public SendMessageTask(Graduate targetGraduate){
this.targetGraduate = targetGraduate;
}
@Override
protected String doInBackground(String... params) {
URL myUrl = null;
HttpURLConnection conn = null;
String response = "";
String data = params[0];
try {
myUrl = new URL("http://your url");
conn = (HttpURLConnection) myUrl.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//one long string, first encode is the key to get the data on your web
//page, second encode is the value, keep concatenating key and value.
//theres another ways which easier then this long string in case you are
//posting a lot of info, look it up.
String postData = URLEncoder.encode("TOKEN", "UTF-8") + "=" +
URLEncoder.encode(targetGraduate.getToken(), "UTF-8") + "&" +
URLEncoder.encode("SENDER_ID", "UTF-8") + "=" +
URLEncoder.encode(MainActivity.curretUser.getId(), "UTF-8") + "&" +
URLEncoder.encode("MESSAGE_DATA", "UTF-8") + "=" +
URLEncoder.encode(data, "UTF-8");
OutputStream os = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
conn.disconnect();
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String s) {
//do what ever you want with the response
Log.d("roee", s);
}
}
答案 2 :(得分:1)
我使用Hashmap而不是List。我是这样做的:
HashMap<String,String> contact=new HashMap<>();
contact.put("name",name);
contact.put("address",add);
try{
URL url=new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postDataStr(contact));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
conn.disconnect();
if (responseCode == HttpURLConnection.HTTP_OK)
return "success";
else
return "";
}catch (Exception e)
{
e.printStackTrace();
}
postDataStr()用于将Hashmap转换为我从某处复制的编码字符串,并将其更改为适合我的应用程序。以下是代码:
private String postDataStr(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
答案 3 :(得分:0)
Whule在这里给出的所有优秀答案都将解决您的问题,我强烈建议您查看一些非常棒的(并广泛使用的)网络库,因为它们会减少您的工作以及随附的错误案例Android进程和方向更改,进程终止等。您应该查看Square的Retrofit库或Google自己的Volley进行网络连接。