How to modify a request body before forwarding it - java

I want to do the same functionality in the HttpPost, using servlets that is, instead of creating the request using HttpPost, I want to use another request coming from a servlet and change body before forwarding it to the URL "www.url.com/cgi-bin", how can I change the body content of a request ?
public void call() throws ClientProtocolException, IOException, InterruptedException {
String url = "www.url.com/cgi-bin"
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(url);
String data = "body data";
InputStream stream = new ByteArrayInputStream(data.getBytes("UTF-8"));
InputStreamEntity reqEntity = new InputStreamEntity(stream, -1);
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
httppost.addHeader("charset", "utf-8");
httppost.setHeader("Content-Type", "text/xml");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
httpclient.getConnectionManager().shutdown();
}
I want it to be like...
#WebServlet("/myServlet/*")
public class MyHandler extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) {
// add data to request here ...
// forward request to the URL ...
}
}

Unfortunately it is not possible, using servlet api's, for a servlet to generate a new post request with body content.

Related

Upload File from GWT to another domain , response is always null

I am uploading a File from GWT to a different domain
File Uploads well , But the response i sent from the server always reaches as "null" at the client side
response.setContentType("text/html");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().print("TEST");
response is NULL only when i upload the file on a different domain ... (on same domain all is OK)
I also see this in GWT documentation
Tip:
The result html can be null as a result of submitting a form to a different domain.
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FormPanel.SubmitCompleteEvent.html
Is there any way I can receive back a response at my client side when i am uploading file to a different domain
There are 2 possible answer:
Use JSONP Builder
JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder();
requestBuilder.requestObject(url, new AsyncCallback<FbUser>() {
#Override
public void onFailure(Throwable ex) {
throw SOMETHING_EXCEPTION(ex);
}
#Override
public void onSuccess(ResponseModel resp) {
if (resp.isError()) {
// on response error on something
log.error(resp.getError().getMessage())
log.error(resp.getError().getCode())
}
log.info(resp.getAnyData())
}
Not to use GWT to upload, rather use other client like apache HttpClient
public uploadFile() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
FileBody bin = new FileBody(new File(UPLOADED_FILE));
long size = bin.getContentLength();
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("PART", bin);
String content = "-";
try {
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity ent = response.getEntity();
InputStream st = ent.getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(st, writer);
content = writer.toString();
} catch (IOException e) {
return "false";
}
return content;
}
Hope it helps

apache http client send url encoded post request

I have a dropwizard service in whitch i implemented a post request who consumes APPLICATION_FORM_URLENCODED media type and uses #FormParam annotation
Then in my client i'm using Apache HttpClient to make a post request like this:
public void sendPost(String path, JsonObject params) throws Exception {
String url = "http://" + TS_API_HOST + ":" + TS_API_PORT + "/" + path;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<String> keys = params.keySet().iterator();
while(keys.hasNext()){
String currentKey = keys.next();
nvps.add(new BasicNameValuePair(currentKey, params.get(currentKey).toString()));
}
System.out.println(nvps.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response.close();
}
}
The url and params I'm passing are correct but i keep getting 400 bad request as a response.
In Postman it works very well...

Oauth token requests before provider credentials issuance

Please forgive me if I ask something stupid, I am a novice here. I need to implement OAuth in my Java application to authenticate against launchpad.net API. The documentation specifies an initiation of a token request with three parameters : oauth_consumer_key e.g. (name of my application), oauth_signature_method e.g. "PLAINTEXT" and oauth_signature e.g. The string "&". I realised that most OAuth libraries require that
I have already acquired a Consumer key and Consumer Id/Secret from
the OAuth provider (e.g as issued in Twitter), and most examples are organised in this manner. However, launchpad.net will issue these parameters only after issuance of request token (they use no third party provider). How can I proceed?I am currently stuck after trying some libraries that threw errors. Many thanks for any useful information. The official launchpad library is in python.
My initial code is below:
public class Quicky {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet("https://launchpad.net/+request-token");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println("Your current GET request status:" + response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
} finally {
response1.close();
}
HttpRequest request;
HttpPost httpPost = new HttpPost("https://launchpad.net/+request-token");
PostMethod poster = new PostMethod();
List <NameValuePair> postParams = new ArrayList <NameValuePair>();
postParams.add(new BasicNameValuePair("oauth_customer_key", "XXXX"));
postParams.add(new BasicNameValuePair("oauth_signature_method", "PLAINTEXT"));
postParams.add(new BasicNameValuePair("oauth_signature", "&"));
httpPost.setEntity(new UrlEncodedFormEntity(postParams, "utf-8"));
// httpPost.setEntity(entity1);
httpclient.execute(httpPost);
HttpParameters requestParams = (HttpParameters) postParams;
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println("Your current POST request status:" + response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
}
} finally {
httpclient.close();
}
}
}
I finally resolved the issue error messages after some research and code re-factoring. The correct code is below, maybe it could be useful to someone out there.
public class LaunchPadTokenRetriever {
public static void main(String[] args) throws ClientProtocolException, IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://launchpad.net/+request-token");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
List <NameValuePair> urlParams = new ArrayList <NameValuePair>();
urlParams.add(new BasicNameValuePair("oauth_signature", "&"));
urlParams.add(new BasicNameValuePair("oauth_consumer_key", "tester"));
urlParams.add(new BasicNameValuePair("oauth_signature_method", "PLAINTEXT"));
httpPost.setEntity(new UrlEncodedFormEntity(urlParams));
CloseableHttpResponse response = httpclient.execute(httpPost);
System.out.println(response);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("Initial credentials ---> "+ responseBody);
System.out.println();
String getresponse = responseBody;
EntityUtils.consume(entity);
} finally {
response.close();
}
}
}

REST PUT with external file JSON to httpClient Java?

I need to translate this for example :
curl -X PUT -u ident:pass -H "Content-Type : application/json" --data-binary #G:\jonJob.json "http://localhost:8080/jobs/"
(this works).
in java with httpClient. I have try a lot of things but nothing work..
Someone could help me please ?
What I've tried :
public class PostFile {
#SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ident", "pass");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPut httppost = new HttpPut("http://localhost:8080/jobs/");
File file = new File("G:/jsonJob.json");
HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("file", file, ContentType.create("application/json"), file.getName()).build();
httppost.setEntity(httpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpClient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
}
}
Result : "HTTP/1.1 415 Not supported type" (unsupported media type)
for your http req headers -H you have java runnable imple with interceptor:
public void run() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(YourConnectionMgr.getInstance())
.addInterceptorLast(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (request.getRequestLine().getMethod() == "POST"){
request.addHeader("Content-Type", "application/json") ;
see examples here to figure out 'connectionManager'
for simple auth, add this
to map in memory and POST a file see answer here
Note, you will eventually want some kind of async http client for java , you can google for that. The apache examples like in the link provided are mostly blocking network calls AFAIK

Submit an httpRequest method post to an apache server with java se

i'm trying to use a website from my java application as i'd do through my browser; it's the first time i'm trying something like this and i'm afraid i'm missing something.
I'm using apache httpcore libraries to do the http requests with the post method, with wireshark i've seen the parameters in the post request and i've added them to the request i do with java; the same for the headers.
If i sniff the request made with java i can't capture the http post request, but only the tcp traffic.
This is how i do the request:
HttpPost httpPost = new HttpPost("http://xxx.xxx");
httpPost.setHeader("Host", "xxx.xxx:xxxx");
.
.
.
HttpParams params = new BasicHttpParams();
params.setParameter("aaaa", "bbbb");
.
.
.
HttpResponse response = httpclient.execute(httpPost);
Am i missing something?
I should check something else?
Thank you very much for the help!
You have to supply a body with your post request, which you do so by calling the .setEntity(HttpEntity) method on your HttpPost.
private void sendToPostProxy(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//the url to forward too
String url = "http://127.0.0.1:"+proxyPort+request.getRequestURI()
+(request.getQueryString()==null?"":"?"+request.getQueryString());
HttpPost get = new HttpPost(url);
//I am streaming requests straight through, but there are many Entity types you can use
get.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));
sendToProxy(request, response, get);
}
private void sendToProxy(HttpServletRequest request,
HttpServletResponse response,HttpRequestBase get) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
Enumeration headers = request.getHeaderNames();
//copy headers
while(headers.hasMoreElements()){
String next = String.valueOf(headers.nextElement());
String header = request.getHeader(next);
if (!get.containsHeader(next)&&!"Content-Length".equalsIgnoreCase(next))
get.addHeader(next, header);
}
try{
//perform post
HttpResponse proxied = client.execute(get);
//set client headers
for (Header h : proxied.getAllHeaders()){
response.setHeader(h.getName(), h.getValue());
}
//stream to client
HttpEntity body = proxied.getEntity();
body.writeTo(response.getOutputStream());
response.setStatus(HttpServletResponse.SC_OK);
}catch(Exception e){
e.printStackTrace();
get.abort();
}
}

Categories