在Android HttpURLConnection类和消费GSON ASP.NET网页API [英] Consuming ASP.NET Web Api from Android HttpUrlConnection and Gson

查看:276
本文介绍了在Android HttpURLConnection类和消费GSON ASP.NET网页API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Heyy大家,
我想从Android使用Web服务,我这样做,从我的Java桌面应用程序,它工作得很好,但是当我试图在Android我有很多的错误。
我已经固定IIS前preSS的localhost的问题。
请,帮助我。

 公共无效SetCloud(视图v){    ConnectionTask任务=新ConnectionTask();    尝试{
        task.execute()获得()。
    }赶上(InterruptedException的E){
        // TODO自动生成catch块
        e.printStackTrace();
    }赶上(为ExecutionException E){
        // TODO自动生成catch块
        e.printStackTrace();
    }
    / *
    HTTP的http = HttpFactory.create(上下文);
    http.post(http://192.168.8.2:57888/api/Employees/AddAccount)
        。数据(新AccountBag(Test123,TestServer12,D19916F-7C51-4AD6-AC24))
        。发送();*/
}
私有类ConnectionTask扩展的AsyncTask<太虚,太虚,字符串> {
    字符串响应code = NULL;
    @覆盖
    保护字符串doInBackground(虚空......为arg0){
      尝试{        网址URL =新的URL(http://192.168.8.2:57888/api/Employees/AddAccount);
          // URL URL =新的URL(http://esprit.azurewebsites.net/api/comments);
        HttpURLConnection的康恩=(HttpURLConnection类)url.openConnection();
        conn.setDoOutput(真);
        conn.setRequestMethod(POST);
        conn.setRequestProperty(内容类型,应用/ JSON);
        AccountBag物镜=新AccountBag(Test123,TestServer12,D19916F-7C51-4AD6-AC24/ *日期时间,AAA,BBBB,CCCC,DDDD,FFFF* /);
        GSON GSON =新GSON();        // java对象转换成JSON格式,
        //并返回JSON格式的字符串
        JSON字符串= gson.toJson(OBJ);        OutputStream的OS = conn.getOutputStream();
        //os.write(input.getBytes());
        os.write(json.getBytes());
        os.flush();        / *如果(conn.getResponse code()!= HttpURLConnection.HTTP_CREATED){
            抛出新的RuntimeException(失败:HTTP错误code:
                + conn.getResponse code());
        } * /
        响应code =+ conn.getResponse code();        BR的BufferedReader =新的BufferedReader(新的InputStreamReader(
                (conn.getInputStream())));        字符串输出;
        的System.out.println(从服务器输出.... \\ n);
        而((输出= br.readLine())!= NULL){
            的System.out.println(输出);
        }        conn.disconnect();      }赶上(MalformedURLException的E){        e.printStackTrace();      }赶上(IOException异常五){        e.printStackTrace();     }
    返回响应code;    }
    }    保护无效onPostExecute(字符串结果){
               //结果是你从你的连接得到了什么
//ConnectionTask.response$c$c.setText(result);    }}


解决方案

 公共类RestAddGroupUser扩展的AsyncTask<名单,LT;用户组>,太虚,字符串> {
私人RestService lRestService;
私人字符串URL;
group_action活动;
ArrayList的<&的LatLong GT; mParam;公共RestAddGroupUser(活动活动){
    URL = GlobalData.baseURL +AddGroupuser
    this.activity =(group_action)活性;
}在preExecute保护无效(){
}
字符串结果=;保护字符串doInBackground(列表<&用户组GT; ... PARAMS){    尝试{        StringEntity连接;
        //创建一个新的HttpClient和邮政头
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(URL);        GSON GSON =新GSON();
        串jsonobj = gson.toJson(PARAMS [0]);
        jsonobj = jsonobj.substring(1,jsonobj.length() - 1);
        EN =新StringEntity(jsonobj,UTF-8);
        en.setContentType(应用/ JSON);        //添加参数
        httppost.setEntity(EN);
        串的JSONObject = gson.toJson(PARAMS [1]);
        的JSONObject = jsonobject.substring(1,jsonobj.length() - 1);
        EN =新StringEntity(的JSONObject,UTF-8);
        en.setContentType(应用/ JSON);        //添加参数
        httppost.setEntity(EN);
        httppost = ServiceUtils.SetPostRequestHeader(httppost,活动);        //执行HTTP POST请求
        HTT presponse响应= httpclient.execute(httppost);
        HttpEntity实体= response.getEntity();
        如果(实体!= NULL){
            的InputStream inStream中= entity.getContent();
            结果= convertStreamToString(插播广告);
        }
    }赶上(ClientProtocolException E){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    }赶上(例外五){
        e.printStackTrace();
    }
    返回结果;
}
公共无效onPostExecute(字符串结果){    GSON GSON =新GSON();
    布尔状态= FALSE;
}
公共静态字符串convertStreamToString(InputStream为){
    读者的BufferedReader =新的BufferedReader(
            新的InputStreamReader(是));
    StringBuilder的SB =新的StringBuilder();    串线= NULL;    尝试{
        而((行= reader.readLine())!= NULL){
            sb.append(行+\\ n);
        }
    }赶上(IOException异常五){
        e.printStackTrace();
    } {最后
        尝试{
            is.close();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
    }
    返回sb.toString();
}

}

Heyy everyone, I'm trying to consume a web service from Android, I did that from my Java Desktop App and it worked fine but when I tried it on Android I had a lot of errors. I already fixed the "localhost" problem with IIS express . Please Help me with that.

public void SetCloud(View v) {

    ConnectionTask task = new ConnectionTask();

    try {
        task.execute().get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    /*
    Http http = HttpFactory.create(context);
    http.post("http://192.168.8.2:57888/api/Employees/AddAccount")
        .data(new AccountBag("Test123", "TestServer12","D19916F-7C51-4AD6-AC24"))
        .send();*/
}


private class ConnectionTask extends AsyncTask<Void, Void, String>{
    String responseCode = null;
    @Override
    protected String doInBackground(Void... arg0) {
      try {

        URL url = new URL("http://192.168.8.2:57888/api/Employees/AddAccount");
          //URL url = new URL("http://esprit.azurewebsites.net/api/comments");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");


        AccountBag obj = new AccountBag("Test123", "TestServer12","D19916F-7C51-4AD6-AC24"/*,"DateTime","aaa","bbbb","cccc","dddd","ffff"*/);
        Gson gson = new Gson();

        // convert java object to JSON format,
        // and returned as JSON formatted string
        String json = gson.toJson(obj);

        OutputStream os = conn.getOutputStream();
        //os.write(input.getBytes());
        os.write(json.getBytes());
        os.flush();

        /*if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }*/
        responseCode = ""+conn.getResponseCode();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }
    return responseCode;

    }
    }

    protected void onPostExecute(String result) {
               // result is what you got from your connection
//ConnectionTask.responseCode.setText(result);

    }

}

解决方案

public class RestAddGroupUser extends AsyncTask<List<UserGroup>,Void,String> {
private  RestService lRestService;
private String url;
group_action activity;
ArrayList<LatLong> mParam;

public RestAddGroupUser(Activity activity) {
    url= GlobalData.baseURL + "AddGroupuser";
    this.activity = (group_action)activity;
}

protected void onPreExecute(){
}
String result = "";

protected String doInBackground(List<UserGroup>... params) {

    try {

        StringEntity en;
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        Gson gson = new Gson();
        String jsonobj=gson.toJson(params[0]);
        jsonobj=jsonobj.substring(1, jsonobj.length()-1);
        en= new StringEntity(jsonobj,"UTF-8");
        en.setContentType("application/json");

        // Add parameters
        httppost.setEntity(en);
        String jsonobject=gson.toJson(params[1]);
        jsonobject=jsonobject.substring(1, jsonobj.length()-1);
        en= new StringEntity(jsonobject,"UTF-8");
        en.setContentType("application/json");

        // Add parameters
        httppost.setEntity(en);
        httppost = ServiceUtils.SetPostRequestHeader(httppost,activity);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inStream = entity.getContent();
            result = convertStreamToString(inStream);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
public void onPostExecute(String result){

    Gson gson =new Gson();
    boolean status = false;


}
public static String convertStreamToString(InputStream is){
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;

    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

这篇关于在Android HttpURLConnection类和消费GSON ASP.NET网页API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆