之前一直写http的请求都是通过开源的异步http。感觉这样子了解的内容太少了,所以就专门将一个登陆的http请求自己写了一遍。
主要代码如下:
public static String httpPost(String url,Map<String,String> params){
try {
URL httpUrl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection)httpUrl.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(5000);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setInstanceFollowRedirects(true);//遵循重定向
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
JSONObject jsonObject = new JSONObject();
for(Map.Entry<String, String> map:params.entrySet()){
jsonObject.put(map.getKey(), map.getValue());
}
dataOutputStream.writeBytes(jsonObject.toString());
dataOutputStream.flush();
dataOutputStream.close();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line;
while((line=bufferedReader.readLine())!=null){
sb.append(line);
}
bufferedReader.close();
urlConnection.disconnect();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}