1.GET请求
public static String getRequest(String path, String param) {
String returnData = "";
String srtUrl = path + "?" + param;
try{
URL url = new URL(srtUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Accept-Charset", "utf-8");
urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestMethod("GET");
urlConn.connect();
int code = urlConn.getResponseCode();
if(code == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
returnData += tempString;
}
reader.close();
}
urlConn.disconnect();
}catch (Exception e) {
e.printStackTrace();
}
return returnData;
}
2.POST请求
public static String postRequest(String path, String param) {
String returnData = "";
String srtUrl = path + "?" + param;
int responseCode;
try {
URL restURL = new URL(srtUrl);
HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setDoOutput(true);
OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
os.write(param);
os.flush();
responseCode = conn.getResponseCode();
if (responseCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
returnData += tempString;
}
reader.close();
} else {
returnData = "false";
}
os.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return returnData;
}
3.举例调用
String getUrl = "your_url";
String getParam = "key1=" + "value1" + "&" + "key2=" + "value2" ;
String get = getRequest(getUrl,getParam);
JSONObject getJson = new JSONObject(get);
getJson.getJSONObject("location").get("name").toString();
String postUrl = "your_url";
String postParam = "key1=" + "value1" + "&" + "key2=" + "value2" ;
String post = postRequest(postUrl,postParam);
JSONObject postJson = new JSONObject(post);
postJson.get("date").toString();
4.需要引用的jar包
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;