Search in sources :

Example 11 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project camel by apache.

the class HttpRouteTest method testPutParameterInURI.

@Test
public void testPutParameterInURI() throws Exception {
    HttpClient client = new HttpClient();
    PutMethod put = new PutMethod("http://localhost:" + port1 + "/parameter?request=PutParameter&others=bloggs");
    StringRequestEntity entity = new StringRequestEntity(POST_MESSAGE, "application/xml", "UTF-8");
    put.setRequestEntity(entity);
    client.executeMethod(put);
    InputStream response = put.getResponseBodyAsStream();
    String out = context.getTypeConverter().convertTo(String.class, response);
    assertEquals("Get a wrong output ", "PutParameter", out);
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) PutMethod(org.apache.commons.httpclient.methods.PutMethod) Test(org.junit.Test)

Example 12 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project camel by apache.

the class HttpProducer method createRequestEntity.

/**
     * Creates a holder object for the data to send to the remote server.
     *
     * @param exchange the exchange with the IN message with data to send
     * @return the data holder
     * @throws CamelExchangeException is thrown if error creating RequestEntity
     */
protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
    Message in = exchange.getIn();
    if (in.getBody() == null) {
        return null;
    }
    RequestEntity answer = in.getBody(RequestEntity.class);
    if (answer == null) {
        try {
            Object data = in.getBody();
            if (data != null) {
                String contentType = ExchangeHelper.getContentType(exchange);
                if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
                    if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
                        throw new CamelExchangeException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
                    }
                    // serialized java object
                    Serializable obj = in.getMandatoryBody(Serializable.class);
                    // write object to output stream
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    HttpHelper.writeObjectToStream(bos, obj);
                    answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
                    IOHelper.close(bos);
                } else if (data instanceof File || data instanceof GenericFile) {
                    // file based (could potentially also be a FTP file etc)
                    File file = in.getBody(File.class);
                    if (file != null) {
                        answer = new FileRequestEntity(file, contentType);
                    }
                } else if (data instanceof String) {
                    // be a bit careful with String as any type can most likely be converted to String
                    // so we only do an instanceof check and accept String if the body is really a String
                    // do not fallback to use the default charset as it can influence the request
                    // (for example application/x-www-form-urlencoded forms being sent)
                    String charset = IOHelper.getCharsetName(exchange, false);
                    answer = new StringRequestEntity((String) data, contentType, charset);
                }
                // fallback as input stream
                if (answer == null) {
                    // force the body as an input stream since this is the fallback
                    InputStream is = in.getMandatoryBody(InputStream.class);
                    answer = new InputStreamRequestEntity(is, contentType);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
        } catch (IOException e) {
            throw new CamelExchangeException("Error serializing message body", exchange, e);
        }
    }
    return answer;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Serializable(java.io.Serializable) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) Message(org.apache.camel.Message) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) GenericFile(org.apache.camel.component.file.GenericFile) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 13 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project Mvp-Rxjava-Retrofit-dagger2 by pengMaster.

the class MediaRecordPresenter method downLoadMediaFile.

/**
 * 下载监督媒体文件
 *
 * @param token
 * @param id
 */
public void downLoadMediaFile(final String token, final String id) {
    ThreadUtils.runThread(new Runnable() {

        @Override
        public void run() {
            HttpClient httpClient = new HttpClient();
            Map<String, String> msg = new HashMap<String, String>();
            msg.put("superviseId", id);
            String params = new Gson().toJson(msg);
            StringRequestEntity paramEntity = null;
            try {
                paramEntity = new StringRequestEntity(params, "application/json", "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            PostMethod postMethod = new PostMethod(Api.GET_MEDIA_RECORD + "?token=" + token);
            postMethod.setRequestEntity(paramEntity);
            try {
                httpClient.executeMethod(postMethod);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                final String resultKey = convertStreamToString(inputStream);
                ThreadUtils.runInMainThread(new Runnable() {

                    @Override
                    public void run() {
                        VideoGsonBean resultKeyBean = new Gson().fromJson(resultKey, VideoGsonBean.class);
                        mRootView.setViewData(resultKeyBean);
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) VideoGsonBean(com.mtm.mrecord.mvp.model.entity.VideoGsonBean) PostMethod(org.apache.commons.httpclient.methods.PostMethod) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HttpClient(org.apache.commons.httpclient.HttpClient) Map(java.util.Map) HashMap(java.util.HashMap)

Example 14 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project Mvp-Rxjava-Retrofit-dagger2 by pengMaster.

the class SplashPresenter method toActDownLoadNetKey.

/**
 * 下载网络请求验证码
 */
private void toActDownLoadNetKey() {
    ThreadUtils.runThread(new Runnable() {

        @Override
        public void run() {
            HttpClient httpClient = new HttpClient();
            Map<String, String> msg = new HashMap<String, String>();
            msg.put("appKey", "9c3d77f18e4848d095e626e9b3a009a3");
            msg.put("appSecret", "ff265c879c4ac08028e77a6c66078f9ce81c15b6fbc76c18f7a12a97c859c92b");
            String params = new Gson().toJson(msg);
            StringRequestEntity paramEntity = null;
            try {
                paramEntity = new StringRequestEntity(params, "application/json", "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            PostMethod postMethod = new PostMethod(Api.POST_KEY);
            postMethod.setRequestEntity(paramEntity);
            try {
                httpClient.executeMethod(postMethod);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                final String resultKey = convertStreamToString(inputStream);
                ThreadUtils.runInMainThread(new Runnable() {

                    @Override
                    public void run() {
                        ResultKeyGsonBean resultKeyBean = new Gson().fromJson(resultKey, ResultKeyGsonBean.class);
                        String access_token = resultKeyBean.getData().getAccess_token();
                        GlobalConstantUtils.setToken(access_token);
                        Observable.create(new ObservableOnSubscribe<String>() {

                            @Override
                            public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                                SystemClock.sleep(2000);
                                e.onNext("");
                                e.onComplete();
                            }
                        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {

                            @Override
                            public void accept(String s) throws Exception {
                                Intent intent = new Intent(AppLifecyclesImpl.mAppContext, MainActivity.class);
                                mRootView.launchActivity(intent);
                                mRootView.killMyself();
                            }
                        });
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) PostMethod(org.apache.commons.httpclient.methods.PostMethod) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Intent(android.content.Intent) IOException(java.io.IOException) MainActivity(com.mtm.mrecord.mvp.ui.activity.MainActivity) ResultKeyGsonBean(com.mtm.mrecord.mvp.model.entity.ResultKeyGsonBean) LoginException(javax.security.auth.login.LoginException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HttpClient(org.apache.commons.httpclient.HttpClient) NonNull(io.reactivex.annotations.NonNull) Map(java.util.Map) HashMap(java.util.HashMap) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 15 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project fabric8 by jboss-fuse.

the class ProxyServlet method handleEntity.

/**
 * Sets up the given {@link PostMethod} to send the same standard
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a standard request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the data to be sent via the {@link EntityEnclosingMethod}
 */
@SuppressWarnings("unchecked")
private void handleEntity(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws IOException {
    // Get the client POST data as a Map
    Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap();
    // Create a List to hold the NameValuePairs to be passed to the PostMethod
    List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
    // Iterate the parameter names
    for (String stringParameterName : mapPostParameters.keySet()) {
        // Iterate the values for each parameter name
        String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
        for (String stringParamterValue : stringArrayParameterValues) {
            // Create a NameValuePair and store in list
            NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
            listNameValuePairs.add(nameValuePair);
        }
    }
    RequestEntity entity = null;
    String contentType = httpServletRequest.getContentType();
    if (contentType != null) {
        contentType = contentType.toLowerCase();
        if (contentType.contains("json") || contentType.contains("xml") || contentType.contains("application") || contentType.contains("text")) {
            String body = IOHelpers.readFully(httpServletRequest.getReader());
            entity = new StringRequestEntity(body, contentType, httpServletRequest.getCharacterEncoding());
            entityEnclosingMethod.setRequestEntity(entity);
        }
    }
    NameValuePair[] parameters = listNameValuePairs.toArray(new NameValuePair[] {});
    if (entity != null) {
    // TODO add as URL parameters?
    // postMethodProxyRequest.addParameters(parameters);
    } else {
        // Set the proxy request POST data
        if (entityEnclosingMethod instanceof PostMethod) {
            ((PostMethod) entityEnclosingMethod).setRequestBody(parameters);
        }
    }
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) ArrayList(java.util.ArrayList) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) Map(java.util.Map)

Aggregations

StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)102 PostMethod (org.apache.commons.httpclient.methods.PostMethod)63 HttpClient (org.apache.commons.httpclient.HttpClient)33 Test (org.junit.Test)23 PutMethod (org.apache.commons.httpclient.methods.PutMethod)19 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)18 IOException (java.io.IOException)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 AuthRequestHandler (org.apache.commons.httpclient.server.AuthRequestHandler)12 HttpRequestHandlerChain (org.apache.commons.httpclient.server.HttpRequestHandlerChain)12 HttpServiceHandler (org.apache.commons.httpclient.server.HttpServiceHandler)12 Header (org.apache.commons.httpclient.Header)9 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9 GetMethod (org.apache.commons.httpclient.methods.GetMethod)9 InputStream (java.io.InputStream)8 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)7 StringWriter (java.io.StringWriter)6 Map (java.util.Map)6 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)6 PutMethod (org.apache.jackrabbit.webdav.client.methods.PutMethod)6