我正在尝试将 JSON数据发布到服务器。使用this page作为模板,因为它使用现代HttpURLConnection
。
虽然我尝试了多种方式,但这只会返回实际页面的HTML帖子。它实际上并不将 JSON数据(作为字符串传递给方法)发布到页面。
我尝试将 JSON数据用作 JSONObject ,但DataOutputStream
不喜欢这样。
我做错了吗?
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
public JSONObject makeHttpRequest(String data) {
urlObj = new URL("MY URL HERE");
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Length", ""+data.length());
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
conn.disconnect();
jObj = new JSONObject(result.toString());
return jObj;
}
答案 0 :(得分:0)
试试这段代码。它正在我的应用程序中工作。
public JSONObject getResponse(String data) {
try {
StringBuilder builder = new StringBuilder();
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
builder.append(line);
}
} else {
builder.append("{status: \"Unable to connect to server.\"}");
}
Log.e("JSONService.java", builder.toString());
JSONObject object = new JSONObject(builder.toString());
return object;
} catch (Exception ex) {
Log.e("JSONService.java", Log.getStackTraceString(ex));
try {
object.put(STATUS, "Exception " + ex.getMessage());
} catch (Exception e) {
Log.e("JSONService.java", Log.getStackTraceString(ex));
}
}
return null;
}