![]() |
有胆有识的便当 · 模拟退火解决“多旅行商问题” - 哔哩哔哩· 7 月前 · |
![]() |
干练的茶壶 · 负鼠(负鼠目、负鼠科动物的通称)_百度百科· 7 月前 · |
![]() |
玩篮球的韭菜 · 国企改革三年行动助推甘肃国企高质量发展跃上新 ...· 1 年前 · |
![]() |
不拘小节的毛衣 · 《从红月开始》的火爆告诉我们,原来科幻小说也 ...· 1 年前 · |
![]() |
玩命的小蝌蚪 · 地铁,国铁,该选哪个?--大兴机场轨道交通运 ...· 1 年前 · |
我已经开发了一个Java代码,可以使用URL和HttpUrlConnection将以下cURL转换为java代码。cURL为:
curl -i 'http://url.com' -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"auth": { "passwordCredentials": {"username": "adm", "password": "pwd"},"tenantName":"adm"}}'
我已经写了这段代码,但它总是给HTTP代码400错误的请求。我找不到丢失的东西。
String url="http://url.com";
URL object=new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
JSONObject cred = new JSONObject();
JSONObject auth = new JSONObject();
JSONObject parent = new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString());
parent.put("auth", auth.toString());
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
wr.flush();
//display what returns the POST request
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
br.close();
System.out.println("" + sb.toString());
} else {
System.out.println(con.getResponseMessage());
}
您的JSON不正确。而不是
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString()); // <-- toString()
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
写
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
因此,对于外部对象,应该只调用一次JSONObject.toString()。
另一件事(很可能不是你的问题,但我想提一下):
为了确保不会遇到编码问题,如果编码不是
UTF-8
,则应指定编码
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
// ...
OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();
您可以使用此代码通过http和json进行连接和请求
try {
URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
+ "&key="+key
+ "&access_token=" + access_token);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
private JSONObject uploadToServer() throws IOException, JSONException {
String query = "https://example.com";
String json = "{\"key\":1}";
URL url = new URL(query);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
JSONObject jsonObject = new JSONObject(result);
in.close();
conn.disconnect();
return jsonObject;
}
我有一个类似的问题,我得到了400,糟糕的请求只有PUT,而作为POST请求是完全正常的。
下面的代码在POST中运行良好,但对PUT的请求不好:
conn.setRequestProperty("Content-Type", "application/json");
os.writeBytes(json);
在进行下面的更改后,POST和PUT都能正常工作
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
os.write(json.getBytes("UTF-8"));
这里是完整的代码和解决方案
PostJSONWithHttpURLConnection.java类
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostJSONWithHttpURLConnection {
String charset = "UTF-8";
HttpURLConnection con;
URL urlObj;
JSONObject jObj = null;
StringBuilder result;
public JSONObject makeHttpRequest(String url,
String paramsJSON) {
try {
urlObj = new URL(url);
con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
try (OutputStream os = con.getOutputStream()) {
byte[] input = paramsJSON.getBytes(charset);
os.write(input, 0, input.length);
int code = con.getResponseCode();
Log.d("HTTP CODE", String.valueOf(code));
} catch (IOException e) {
e.printStackTrace();
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(con.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
con.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return jObj;
}
在doInBackground上使用代码(字符串...strArr)
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
String writeValueAsString = objectMapper.writeValueAsString(jSONObject);