由于过去几个小时的痛苦,我一直在尝试以Java方式发送简单的http请求。由于我实际上是一名Python编程专家,因此我发现发送这样一个简单请求所需的代码太多了。
我很难相信发送一个简单的get
或post
请求会占用Java中太多的代码行。我是否缺少任何特定的图书馆?如果是这样,哪一个?
如果不是,那么Java为什么需要那么多代码来发送简单请求。
这是我需要编写的代码以完成任务……
class movie_interface
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
movie_interface http = new movie_interface();
Log.d("api" , "Testing 1 - Send Http GET request");
http.sendGet();
}
// HTTP GET request
public void sendGet() throws Exception {
System.out.println("API sendGet running");
URL url = new URL("https://api.themoviedb.org/3/movie/upcoming");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
Map<String, String> parameters = new HashMap<>();
parameters.put("api_key", "myapikey");
parameters.put("region", "IN");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
Log.d("api" , "writing bytes") ;
out.writeBytes(getParamsString(parameters));
out.flush();
out.close();
Log.d("api" , "done writing bytes") ;
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
// Reading the response
int status = con.getResponseCode();
Log.d("api" , "Got response with code : "+ Integer.toString(status)) ;
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
Log.d("api" , content.toString()) ;
}
public static String getParamsString(Map<String, String> params)
throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
String resultString = result.toString();
return resultString.length() > 0
? resultString.substring(0, resultString.length() - 1)
: resultString;
}
}
我正在android中使用此代码。我认为,仅凭一个请求使用spring就会太过分了。
执行DataOutputStream out = new DataOutputStream(con.getOutputStream());
行后,我也立即收到异常。