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
Related
I've got a curl call like this:
curl -i -X POST -H "Content-Type: multipart/form-data" -F "file=#data_test/json_test.json" http://domain.com/api/upload_json/
All I need to do is a Java implementation for this call. I've already made this code, but the file, which appears to server, seems to be null.
public static void uploadJson(String url, File jsonFile) {
try {
HttpPost request = new HttpPost(url);
EntityBuilder builder = EntityBuilder
.create()
.setFile(jsonFile)
.setContentType(ContentType
.MULTIPART_FORM_DATA)
.chunked();
HttpEntity entity = builder.build();
request.setEntity(entity);
HttpResponse response = getHttpClient().execute(request);
logger.info("Response: {}", response.toString());
} catch (IOException e) {
logger.error(e.getMessage());
}
}
What is the proper way to build this request?
CloseableHttpClient httpClient = HttpClientBuilder.create()
.build();
HttpEntity requestEntity = MultipartEntityBuilder.create()
.addBinaryBody("file", new File("data_test/json_test.json"))
.build();
HttpPost post = new HttpPost("http://domain.com/api/upload_json/");
post.setEntity(requestEntity);
try (CloseableHttpResponse response = httpClient.execute(post)) {
System.out.print(response.getStatusLine());
EntityUtils.consume(response.getEntity());
}
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();
}
}
}
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.
my problem is, that i don't get, how to log in with Java and Apache HttpComponents (HttpClient v4.5.1) into a specific site: Site im trying to log in. I have the username (test_admin) and the password (testing) to log in but i think this is not enough and i need something more. I think this has something to do with the field security_token i see when i make a get request to the uri, but i dont know how to keep that or how to save that and what to do with it afterwards. There is also a hidden input field with the name login-ticket, but i dont know what's that for either. I want to login, because i need to see the courses and add some new ones. After trying with several code implementations im stick with this code:
public static void setGet(CloseableHttpClient httpClient) throws UnsupportedOperationException, IOException
{
HttpGet httpGet = new HttpGet("http://demo.studip.de/dispatch.php/admin/courses");
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("GET Response Status:: "
+ httpResponse.getStatusLine().getStatusCode());
showEntity(httpResponse,httpResponse.getEntity());
}
public static HttpEntity setParam(int count, String[] params, String[] values)
{
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (int i = 0; i < count; i++)
{
formparams.add(new BasicNameValuePair(params[i],values[i]));
System.out.println("Paramater------------------> "+params[i]+" Values-------------> "+values[i]);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
return entity;
}
public static void setPost(HttpClient httpC) throws ClientProtocolException, IOException
{
HttpPost httppost = new HttpPost("http://demo.studip.de/dispatch.php/admin/courses");
//String[] params = {"loginname", "password"};
//String[] values = {"test_admin", "testing"};
//HttpEntity entity = setParam(2, params, values );
HttpResponse response = httpC.execute(httppost);
System.out.println("POST Response Status:: "
+ response.getStatusLine().getStatusCode());
showEntity(response, response.getEntity());
}
public static void showEntity(HttpResponse httpResp, HttpEntity httpClient) throws IOException
{
httpClient = httpResp.getEntity();
if (httpClient != null)
httpClient = new BufferedHttpEntity(httpClient);
System.out.print(EntityUtils.toString(httpClient));
}
public static void main(String[] args) throws InterruptedException, IOException {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("test_admin", "testing"));
CloseableHttpClient hc =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
setGet(hc);
// HttpClient httpclient = HttpClients.createDefault();
setPost(hc);
setGet(hc);
}
The problem now ist that i get everytime the same answer from the server i only see the login page in the response, where the server asks me to login with username and password.
Which code you get from the server 401,403,301,302 or 200?
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();
}
}