【发布时间】:2015-10-27 17:12:57
【问题描述】:
我需要向我的 Web 服务发送一个字符串,但我对如何使用 HttpURLConnection 发送字符串有疑问。
Obs:在字符串“结果”中我有类似的东西:
{"sex":"Famale","nome":"Larissa Aparecida Nogueira","convenios":[{"convenio":2,"tipo":"Principal","number":"44551-1456-6678-3344"}],"user":"lari.ap","email":"lari.ap@yahoo.com.br","cell":"(19)98167-5569"}
以下是我的代码:
public UsuerService(Context context, String result) {
this.progressDialog = new ProgressDialog(context);
this.context = context;
this.result = result;
}
@Override
protected String doInBackground(String... params) {
String responseString = "";
try {
URL url = new URL(Constants.USUARIO + "/createUsuario");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
result = response.toString();
bufferedReader.close();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}
return null;
}
我有一个类可以提取我的数据并将其解析为 JsonObject。 我需要了解如何使用 HttpURLConnection 为 Web 服务发送我的 object.toString()。
以下是代码:
public String parserUsuarioJson(){
JSONObject object = new JSONObject();
try {
object.put(Constants.KEY_NAME, mUsuario.getNome());
object.put(Constants.KEY_EMAIL, mUsuario.getEmail());
object.put(Constants.KEY_USER, mUsuario.getUser());
object.put(Constants.KEY_PASS, mUsuario.getSenha());
object.put(Constants.KEY_SEX, mUsuario.getSexo());
object.put(Constants.KEY_CELLPHONE, mUsuario.getCelular());
JSONArray array = new JSONArray();
for(int i = 0; i < mUsuario.getUsuarioConvenios().size() ; i++){
JSONObject convenio = new JSONObject();
convenio.put(Constants.KEY_CONVENIO, mUsuario.getUsuarioConvenios().get(i).getConvenio().getId());
convenio.put(Constants.KEY_NUMBER, mUsuario.getUsuarioConvenios().get(i).getNumero());
convenio.put(Constants.KEY_TYPE, mUsuario.getUsuarioConvenios().get(i).getTipo());
array.put(convenio);
}
object.put(Constants.KEY_CONVENIOS, array);
} catch (JSONException e) {
Log.e("Register", e.getMessage());
}
return object.toString();
}
提前致谢。 :)
【问题讨论】:
-
对 android 中的所有 NetworkCalls 使用 volley。它的谷歌库,非常易于使用。 developer.android.com/training/volley/index.html
-
您应该将信息化名,因为您刚刚在互联网上发布了一些女性手机号码!
标签: android json httpurlconnection