以下代码有效但我试图将Json插入到Http请求体中,我不知道我是否正在构建请求。我想知道在发送请求之前如何打印请求。
private class LoginAsync1 extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params)
{
Log.d(TAG, "doInBackground: ");
String reply = sendPost("http://10.160.35.32:888/api/User/Login");
Log.d(TAG, "reply: " + reply);
return null;
}
}
private String sendPost(String searchQuery)
{
Log.d(TAG, "sendPost: ");
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
OutputStreamWriter wr = null;
InputStream is_response = null;
HttpURLConnection con = null;
try
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("LoginName", "bbbbb");
jsonObject.put("Password", "bbbbb");
jsonObject.put("LanguageCode", "en");
String message = jsonObject.toString();
URL url = new URL(searchQuery);
if (url.getProtocol().toLowerCase().equals("https"))
{
Log.w(TAG, "url.getProtocol().toLowerCase().equals('https')");
return "failure";
}
else
{
con = (HttpURLConnection) url.openConnection();
}
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setFixedLengthStreamingMode(message.getBytes().length);
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Content-Type", "application/json");
wr = new OutputStreamWriter(con.getOutputStream());
wr.write(message);
wr.flush();
String req = con.getContent().toString();
Log.d(TAG, "req");
Log.d(TAG, req);
con.connect();
is_response = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(is_response));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
Log.d(TAG, "line: " + line);
}
}
catch (IOException e)
{
Log.e(TAG, "IOException", e);
return null;
}
catch (Exception e)
{
Log.e(TAG, "Exception ", e);
return null;
}
finally
{
try
{
if(wr != null)
{
wr.close();
Log.d(TAG, "wr.close()");
}
else
{
Log.d(TAG, "wr == null");
}
if(is_response != null)
{
is_response.close();
Log.d(TAG, "is_response.close()");
}
else
{
Log.d(TAG, "is_response == null");
}
if(reader != null)
{
reader.close();
Log.d(TAG, "reader.close()");
}
else
{
Log.d(TAG, "reader == null");
}
if(con != null)
{
con.disconnect();
Log.d(TAG, "con disconnected");
}
else
{
Log.d(TAG, "con == null");
}
}
catch (IOException e)
{
Log.e(TAG, "", e);
}
}
return builder.toString();
}
答案 0 :(得分:0)
这可能不是您问题的直接答案,但您可以通过使用OkHttp为您的请求大量简化代码 - http://square.github.io/okhttp/
然后,要获得正确的日志记录机制,您可以使用okhttp-logging-interceptor - https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor。