Skip to content

Commit

Permalink
Merge pull request #39 from gitzhouxinyu1/master
Browse files Browse the repository at this point in the history
修复使用TypeConfig.METHOD_GET模式依然以POST方式请求json文件的问题
  • Loading branch information
MZCretin authored Apr 22, 2022
2 parents b6e5fa4 + 9d49667 commit 32c62fb
Showing 1 changed file with 17 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void run() {
// 根据URL地址创建URL对象
url = new URL(urlString);

httpURLConnection = obtainConnection(url, "", headers);
httpURLConnection = obtainConnection(url, "", headers, false);

httpURLConnection.setRequestMethod("GET");

Expand Down Expand Up @@ -93,7 +93,7 @@ public void run() {

/**
* /**
* GET方法 返回数据会解析成cls对象
* POST方法 返回数据会解析成cls对象
*
* @param context 上下文
* @param urlString 请求的路径
Expand Down Expand Up @@ -127,7 +127,7 @@ public void run() {
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urlString);
httpURLConnection = obtainConnection(url, paramsStr.toString(), headers);
httpURLConnection = obtainConnection(url, paramsStr.toString(), headers, true);

httpURLConnection.setRequestMethod("POST");

Expand Down Expand Up @@ -169,7 +169,7 @@ public void run() {
});
}

private static HttpURLConnection obtainConnection(URL url, String params, Map<String, Object> headers) throws IOException {
private static HttpURLConnection obtainConnection(URL url, String params, Map<String, Object> headers, boolean usePostMethod) throws IOException {
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-type", "application/json");

Expand All @@ -184,17 +184,19 @@ private static HttpURLConnection obtainConnection(URL url, String params, Map<St

// 设置运行输入
httpURLConnection.setDoInput(true);
// 设置运行输出
httpURLConnection.setDoOutput(true);

if (!TextUtils.isEmpty(params)) {
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(params);
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
if (usePostMethod) {
// 设置运行输出
httpURLConnection.setDoOutput(true);
if (!TextUtils.isEmpty(params)) {
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(params);
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
}
}
// TODO: GET的参数会写在URL上
return httpURLConnection;
}
}
}

0 comments on commit 32c62fb

Please sign in to comment.