我有一組對象,我試圖通過API發佈。第一個對象將通過它應該,然後我得到:URLConnection - 讀取響應後無法寫入請求主體
java.net.ProtocolException: cannot write request body after response has been read
我相當肯定,它只是在我做事情的順序,但我仍然在學習Android和一直在努力找出一個小時,現在一點。
想到我會轉向你們尋求幫助!我需要接收對POST的每個響應,所以我可以將它設置爲稍後使用的ID字段。你會看到我在我的FOR循環中解析它,然後將ID存儲在一個列表中,我將稍後循環。
代碼下面的POST:
try {
url = new URL("##Edited Out##");
conn = (HttpsURLConnection) url.openConnection();
// Create the SSL connection
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
// Use this if you need SSL authentication
String userpass = "##Edited Out##:##Edited Out##";
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Content-Type", "application/json;odata=verbose");
// set Timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
JSONObject juo = new JSONObject();
for (int i = 0; i<objects.size(); i++){
juo.put("Field1", "Data for field 1 here");
juo.put("Field2", "Data for field 2 here");
juo.put("Field3", "Data for field 3 here");
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(juo.toString());
wr.flush();
wr.close();
Log.d("ITEM STRING", juo.toString());
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "utf-8"));
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
Log.d("HTTP BR", "" + sb.toString());
jObject = XML.toJSONObject(sb.toString());
Log.d("JSON OBJECT", jObject.toString());
JSONObject menuObject = jObject.getJSONObject("entry");
JSONObject contentObject = menuObject.getJSONObject("content");
JSONObject propertiesObject = contentObject.getJSONObject("m:properties");
JSONObject productObject = propertiesObject.getJSONObject("d:Product_Id");
String retProId = productObject.getString("content");
partIDs.add(retProId);
Log.d("PART ID", retProId);
}
int HttpResult = conn.getResponseCode();
Log.d("HTTP RESULT", String.valueOf(HttpResult));
Log.d("HTTP RESPONSE", conn.getResponseMessage());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
編輯:下面 關於重複的評論我收到的錯誤是稍有不同。我理解它的原理,但我的.getRespondeCode不在我的for循環中,它應該循環。但事實並非如此。
此錯誤發生,如果objects.size> = 2
我需要獲得服務器響應字符串爲每個對象發佈爲它含有一個ID我需要解析。
的可能的複製[讀取輸入後不能寫輸出(http://stackoverflow.com/questions/11413028/cannot-write-output-after-reading-input) – e4c5