Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Sankame
Last active May 9, 2018 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sankame/561d4244e309efd1b9f8f4c2aa72e714 to your computer and use it in GitHub Desktop.
Save Sankame/561d4244e309efd1b9f8f4c2aa72e714 to your computer and use it in GitHub Desktop.
サーバーからのレスポンスが多くてもOK
public JSONObject post(String urlString) throws Exception{
URL url = new URL(urlString);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setConnectTimeout(Const.HTTP_CONNECT_TIMEOUT);
con.setReadTimeout(Const.HTTP_READ_TIMEOUT);
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
con.setChunkedStreamingMode(0);
con.connect();
OutputStream out = con.getOutputStream();
out.write( this.values.getBytes("UTF-8") );
out.flush();
out.close();
final int status = con.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
con.disconnect();
throw new Exception("通信に失敗しました\nお手数ですが、しばらくしてから再度お試し下さい");
}
// BufferedReader reader = new BufferedReader(
// new InputStreamReader(con.getInputStream())
// );
// (3)
final InputStream inputStream = con.getInputStream();
final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
final BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder builder = new StringBuilder();
String body;
while ((body = reader.readLine()) != null) {
builder.append(body);
}
// (4)
reader.close();
inputStreamReader.close();
inputStream.close();
con.disconnect();
String jsonData = builder.toString();
return new JSONObject(jsonData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment