【发布时间】:2015-07-17 09:19:31
【问题描述】:
我想使用 GET 请求将包含登录信息的json 数据发送到webservice。我现在正在做的事情如下,
public JSONObject getJsonData(String url) {
StringBuilder stringBuilder = new StringBuilder();
JSONObject jsonObject = new JSONObject();
JsonObject jsonSend = new JsonObject();
jsonSend.addProperty("email","email@gmail.com");
jsonSend.addProperty("password","*********");
HttpURLConnection conn = null;
try {
URL url1 = new URL(url.toString());
conn = (HttpURLConnection) url1
.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput (true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.connect();
OutputStream out = null;
out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(jsonSend.toString());
Log.e("jsondata", jsonSend.toString());
writer.close();
out.close();
conn.getResponseCode();
InputStreamReader in = new InputStreamReader(
conn.getInputStream());
int b;
while ((b = in.read()) != -1) {
stringBuilder.append((char) b);
}
try {
Log.e("stringbuilder",stringBuilder.toString());
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException je) {
Toast.makeText(this, "Error while creating json", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
try {
// Toast.makeText(getApplicationContext()," code", Toast.LENGTH_SHORT).show();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
finally {
conn.disconnect();
}
return jsonObject;
}
即使我将请求方法指定为 GET,它也会尝试将数据插入webservice。 webservice 具有 php 代码,如果用户凭据有效并且它接受 GET 请求,它将接受 json 数据并返回 json 数据。请让我知道如何解决这个问题。谢谢..
【问题讨论】:
-
您可以将 url 作为 json 字符串发送。
-
您可以发送 url,但这是个坏主意。更好地使用 POST
-
如果您使用的是 Retrofit,您可以将您的 JSON 信息放在标头中并以正常方式发出 get 请求。
-
如果您将登录信息发送到服务器,则使用
authorization标头。我猜这是最好的主意。
标签: php android json web-services httpurlconnection