如何使用jersey和HttpURLConnection发送String

时间:2015-12-22 13:08:46

标签: java android web-services jersey httpurlconnection

我正在尝试将一个文本字符串作为response的一部分从Jersey webservice发送到Android应用程序。

这是webservice接收请求并返回响应的方式:

控制器

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
     @Path("/retrieve/some/text")
       @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
       @Produces(MediaType.APPLICATION_JSON)
       public Response retrieveSomeText(@FormParam("email") String email){

            User user = new User();
            user.setEmail(email);
            return new UserService(user).retrieveSomeText();

       }

服务

import javax.ws.rs.core.Response;
    public Response retrieveSomeText() {
        Response response = Response.status(200).entity("some text to send").build();

        return response;
    }

Android应用使用`HttpURLConnection:

发送请求
public String retrieveSomeText(String email, String method){
        String securityQuestion = "";
        try {
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setReadTimeout(10000);
            con.setConnectTimeout(15000);
            con.setRequestMethod(method);
            con.setDoInput(true);
            con.setDoOutput(true);

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("email", email));
            OutputStream os = con.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(params));
            writer.flush();
            writer.close();
            os.close();

            con.connect();
            securityQuestion = con.getResponseMessage();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return securityQuestion;
    }

响应消息为“已创建”。如何获取我作为Web服务响应的一部分发送的文本字符串?

2 个答案:

答案 0 :(得分:1)

我的建议是尝试使用泽西休息客户端,您可以轻松获得回复。

docs

请参阅以下代码,

try {
    Client client = Client.create();
    WebResource webResource = client
       .resource("http://localhost:8080/your_app_name/retrieve/some/text");
    ClientResponse response = webResource.accept("application/json")
               .post(ClientResponse.class);
    String output = response.getEntity(String.class);
    System.out.println(output);

  } catch (Exception e) {

    e.printStackTrace();

  }

答案 1 :(得分:-1)

你可以在android

中做这样的事情
    final StringBuilder resp = connect(serverUrl.toString(), null, true);

    try {
        final JSONObject json = new JSONObject(resp.toString());
// if an array is retreived, use final JSONArray jsonArr = new JSONArray(resp.toString());
    } catch (JSONException e) {
        throw new LectopolisExcepcion(e);
    }

连接位置

/**
     * Ejecuta un sertvico contra el servidor
     *
     * @param serverUrl
     *            URL de acceso
     * @param datos
     *            Datos en formato JSON. Si viene informado hacemos un POST, en otro caso un GET
     * @return Respuesta
     */
    private StringBuilder connect(String serverUrl,
                                   Object datos,
                                   boolean esSeguro) throws MyExcepcion {


        try {
            final long ini = System.currentTimeMillis();

            final HttpResponse response = ejecutaServicio(serverUrl, datos, esSeguro);

            final StatusLine statusLine = response.getStatusLine();
            final int statusCode = statusLine.getStatusCode();

            StringBuilder builder = new StringBuilder();

            if (statusCode == 200) {
                builder = decodeRespuesta(response);
            } else {
                Log.e(this.getClass().getName(), "Failed to download file. StatusCode: " + statusCode);
            }

            final long fin = System.currentTimeMillis();
            LLog.i("Tiempo proceso: " + (fin - ini));

            return builder;

        } catch (IOException e) {
            LLog.e("Error en la ejecucion del servicio", e);
            throw new MyExcepcion(e);
        }
    }

并使用

private HttpResponse ejecutaServicio(String serverUrl,
                                         Object datos,
                                         boolean esSeguro)  throws MyExcepcion, CambioTerminalExcepcion {

        StringBuilder builder = new StringBuilder();

        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILIS);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_DATOS_MILIS);
        final HttpClient client = new DefaultHttpClient(httpParams);

        HttpUriRequest request;

        try {
            if (datos != null) {
                request = new HttpPost(Constantes.HOST + serverUrl.replaceAll(" ", "%20"));

                final StringEntity s = new StringEntity(datos.toString(), HTTP.UTF_8);

                s.setContentEncoding("UTF-8");
                s.setContentType("application/json");

                ((HttpPost) request).setEntity(s);
                request.addHeader("accept", "application/json");

            } else {
                request = new HttpGet(Constantes.HOST + serverUrl.replaceAll(" ", "%20"));
            }

            if (esSeguro) {
                request.addHeader("Authorization", getAuthHeader());
            }

            Log.d(Constantes.TAG, "Invocando URL: " + Constantes.HOST + serverUrl.replaceAll(" ", "%20"));

            // Indicamos que aceptamos gzip en la respuesta, para poder
            // traer los datos comprimidos
            request.addHeader("Accept-Encoding", "gzip,deflate");
            final HttpResponse response = client.execute(request);

            return response;
        } catch (IOException | NoSuchAlgorithmException e) {
            Log.d(Constantes.TAG, e.getMessage(), e);
            throw new MyExcepcion(e);
        }
    }

    /**
     * Interpreta la respuesta del servidor
     *
     * @param response
     *            Respuesta
     * @return StringBuilder con el contenido de la respuesta
     * @throws IllegalStateException
     *             Illegal state
     * @throws IOException
     *             io exception
     */
    private StringBuilder decodeRespuesta(HttpResponse response) throws IOException {

        final StringBuilder builder = new StringBuilder();

        final HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = null;

        Header contentEncoding = response.getFirstHeader("Content-Encoding");

        // Si la respuesta esta comprimida, la tratamos adecuadamente
        if (contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding.getValue())) {
            Log.i("L", "Respuesta comprimida");
            content = new GZIPInputStream(content);
            byte[] tByte = new byte[1024];

            while (true) {
                int iLength = content.read(tByte, 0, 1024);

                if (iLength < 0) {
                    break;
                }
                builder.append(new String(tByte, 0, iLength, HTTP.UTF_8));
            }
        } else {
            Log.i("L", "Respuesta no comprimida");
            reader = new BufferedReader(new InputStreamReader(content, HTTP.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        }

        if (reader != null) {
            reader.close();
        }

        content.close();

        return builder;
    }

这是json响应的一般方法。我使用基本身份验证,你可以忽略它。我也接受gzip回复。

对于一些西班牙语代码感到抱歉。