Tom
Tom

Reputation: 61

How to perform HTTP Post request in Java?

I know this question had several answers but none of them seem to work for my case.

The operation I'm trying to do in curl is curl -u 'user:pwd' https://localhost:8000/services/search/jobs --data search='search index=my_index'

For instance, I am able to do this in python with:

import urllib
import httplib2
from xml.dom import minidom

baseurl = 'https://localhost:8000'
userName = 'user'
password = 'pwd'
searchQuery = 'index=my_index'
serverContent = httplib2.Http(disable_ssl_certificate_validation=True).request(baseurl + '/services/auth/login',
                                                                               'POST', headers={}, body=urllib.parse.urlencode({'username':userName, 'password':password}))[1]
sessionKey = minidom.parseString(serverContent).getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue
searchQuery = searchQuery.strip()
if not (searchQuery.startswith('search') or searchQuery.startswith("|")):
    searchQuery = 'search ' + searchQuery
print (httplib2.Http(disable_ssl_certificate_validation=True).request(baseurl + '/services/search/jobs','POST',
                                                                   headers={'Authorization': 'Splunk %s' % sessionKey},body=urllib.parse.urlencode({'search': searchQuery}))[1])

But every solution I looked at for java does not seem to work for me. Is there an equivalent of httplib2.Http(disable_ssl_certificate_validation=True).request(...) in Java?

This is what I've tried

String rawData = "search='search index=my_index'";
System.out.println(rawData);
String encodedData = URLEncoder.encode( rawData, "UTF-8" );
String name = "user";
String password = "pwd";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL u = new URL("https://localhost:8000/services/search/jobs");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int code = conn.getResponseCode();
System.out.println("Response    (Code):" + code);
System.out.println("Response (Message):" + conn.getResponseMessage());
DataInputStream input = new DataInputStream(conn.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while ((c = input.read()) != -1) {
  resultBuf.append((char) c);
}
input.close();
System.out.print(resultBuf.toString());**/

Upvotes: 0

Views: 159

Answers (1)

Danny Piper
Danny Piper

Reputation: 73

I have been able to use Jsoup for most of my http needs (mostly web scraping).

Here is some code to post an event I have pulled from javacodeexamples.com

https://www.javacodeexamples.com/jsoup-post-form-data-example/822

Response response = 
                Jsoup.connect("http://www.example.com/postpage")
                .userAgent("Mozilla/5.0")
                .timeout(10 * 1000)
                .method(Method.POST)
                .data("txtloginid", "YOUR_LOGINID")
                .data("txtloginpassword", "YOUR_PASSWORD")
                .data("random", "123342343")
                .data("task", "login")
                .data("destination", "/welcome")
                .followRedirects(true)
                .execute();

Upvotes: 1

Related Questions