This question already has answers here:
Add custom headers to WebView resource requests - android
(11 answers)
Closed 2 years ago.
I need to add custom headers to EVERY request coming from the WebView. I know loadURL has the parameter for adding extra Headers, but those are only applied to only some of the requests.
All (resource related) requests do not contain the headers.
I have looked at all overrides in WebViewClient, but nothing allows for adding headers to resource requests - onLoadResource(WebView view, String url) and shouldInterceptRequest(Webview,url). Any help would be wonderful.
shouldInterceptRequest(Webview,url) can help you to intercept every request of a site, such as JavaScript, CSS, Image. Then inside shouldInterceptRequest(Webview,url) you can use the parameter url to initial new http request by using HttpClient and HttpPOST, here is example code :
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(<"your url for each request">);
httpPost.setHeader("<header-name>", "<header-value>");
HttpReponse httpResponse = client.execute(httpPost);
//here omit getting content-type and encoding
InputStream reponseInputStream = httpReponse.getEntity().getContent();
Then you can put responseInputStream to return WebResourceResponse(<content-type>, <encoding>, reponseInputStream) in your shouldInterceptRequest(Webview,url)
if you have any request which doesn't need add more header, just filter it and return null, shouldInterceptRequest(Webview,url) will do the rest.
Hope this can help.
Related
This question already has answers here:
Handling HttpClient Redirects
(5 answers)
Closed 9 years ago.
I had an issue a few weeks ago in a WebView where it wasn't following redirects as a normal browser would. I used the following suggestion given in many SO answers:
String newUrl = response.getFirstHeader("Location").getValue();
but it only gave 1 step of redirection, but not more, which it needed to. I got around it by repeatedly listening for redirects and manually going through each step.
Now I'm using the following code:
HttpClient httpClient = MyApp.getHttpClient();
HttpPost httpPost = new HttpPost(con.getString(R.string.platform_url_getBalances));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("sid", String.valueOf(sessionKey)));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = null;
// Execute HTTP Post Request. Response body returned as a string
response = httpClient.execute(httpPost, responseHandler);
Recently the end-point for the R.string.platform_url_getBalances changed but we put in a 302 redirect to a different URL. It works fine in a browser and on the iPad version of the app but for Android I get org.apache.http.client.HttpResponseException: Not Found.
I find it very strange that Android is such a pain when it comes to redirecting. Why does it behave like this and is there a reasonable way around it?
Actually, the answer I linked to in my comment is for HttpClient 4.1, near as I can tell, and Android's is older.
My guess is that the equivalent process in Android's version of HttpClient would be do:
Create a subclass of DefaultRedirectHandler that overrides isRedirectRequested() as appropriate for your app
Create a subclass of DefaultHttpClient and override createRedirectHandler() to return an instance of the subclass you created in the previous step
Use your subclass of DefaultHttpClient as a replacement for DefaultHttpClient itself wherever you are creating that instance
Im coding a RESTful API & Android client at the same time as I go and im currently working on pulling the users profile from the server. I feel like this should definitely be a get request being that im only pulling existing data and im not adding/editing anything to my database, but I do need a user_id param to be able to query for the appropriate profile. Can I send just one tiny little variable along with my HttpGet some how or am i supposed to use a HttpPost in this situation regardless?
Android uses Apache's HTTPClient. So, copying their tutorial code:
public void sendStringTo(String remoteUrl, String myString) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remoteUrl+"?string1="+myString);
HttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST either fully consume the response content or abort request
// execution by calling HttpGet#releaseConnection().
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
httpGet.releaseConnection();
}
return;
}
GET can support adding variables/parameters. For example you could make a Url that looks like this:
http://yourwebsite.com/script.php?user_id=19898424
I am working on an android application. In my app i have to open some image and pdf from webservice.I could open the image by using following code.
HttpGet httpRequest = new HttpGet(URL);
httpRequest.addHeader("Accepts", "application");
httpRequest.addHeader("User-Authentication",
"c2hpbmVAaWxlYWZzb2x1dGlvbnMuY29tOnNoaW5laWxlYWY=");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
ANd now I have to open pdf in a webview.So I write the folowing code
WebView mWebView=new WebView(MyPdfViewActivity.this);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Accepts", "application");
map.put("User-Authentication", "c2hpbmVAaWxlYWZzb2x1dGlvbnMuY29tOnNoaW5laWxlYWY=");
mWebView.loadUrl(URL,map);
But I am getting authentication header is not available error. Because of this problem my project is stuck. I find a same type problem here.
check this answer here the accepted answer is "You would need to fetch the page yourself (e.g., via HttpClient) and load it into the WebView that way". How Can I do this?.
Please help me to fix the issue friends.
Look into the documentation.
additionalHttpHeaders
The additional headers to be used in the HTTP request for this URL, specified as a map from name to value. Note that if this map contains any of the headers that are set by default by this WebView, such as those controlling caching, accept types or the User-Agent, their values may be overriden by this WebView's defaults.
Probably your User-Authentication header is also overriden.
I am trying to retrieve a JSON file from a web service using the following URL. That works fine when I use a browser to send the HTTP request.
For the Android application I came up with the following code.
// Android request
String url = "http://data.wien.gv.at/daten/geoserver/ows?service=WFS" +
"&request=GetFeature&version=1.1.0&typeName=ogdwien:BAUMOGD" +
"&srsName=EPSG:4326&outputFormat=json" +
"&bbox=16.377681,48.211448,16.379829,48.21341,EPSG:4326" +
"&maxfeatures=10"
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Though, EntityUtils does not output a JSON file but this XML exception.
// Value of result
<?xml version="1.0" encoding="UTF-8"?>
<ows:ExceptionReport version="1.0.0"
xsi:schemaLocation="http://www.opengis.net/ows http://data.wien.gv.at/daten/geoserver/schemas/ows/1.0.0/owsExceptionReport.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ows="http://www.opengis.net/ows">
<ows:Exception exceptionCode="NoApplicableCode">
<ows:ExceptionText>java.io.EOFException: input contained no data
input contained no data</ows:ExceptionText>
</ows:Exception>
</ows:ExceptionReport>
I hope you can see what wents wrong ...
The HTML specifications technically define the difference between "GET" and "POST" so that former means that form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. > [source]
Since you do encode the full request into the URL (request=GetFeature etc.) => use HttpGet instead.
Might even work imo with post since the url should still be transmitted to the server but the server would need to detect that the post request is actually a get request and behave accordingly.
I need to send a byte arrray file using WCF rest services. I have to send the data using HttpPost method in android. The code which i am using give the status as HTTP/1.1 400 Bad Request error.
private final static String URI = "http://192.168.1.15/QueryService/Import/Test";
final HttpPost request = new HttpPost(URI);
final HttpClient httpClient = new DefaultHttpClient();
final ByteArrayEntity entity = new ByteArrayEntity(fileToBytes(pathToOurFile));
entity.setContentType("application/octet-stream");
entity.setChunked(true);
request.setEntity(entity);
final HttpResponse hr = httpClient.execute(request);
final StatusLine status = hr.getStatusLine();
httpClient.getConnectionManager().shutdown();
It is difficult to tell what is wrong with your request. The standard way of resolving this kind of errors is:
Create a WCF client for your service. Verify that it works as expected.
Use Fiddler or another suitable tool to intercept the HTTP request your client is generating. Both the headers and the body are important.
Modify your Android request to generate the exact same request as the WCF client.
I was also facing same problem with WCF service. 400 Bad request means request parameter value which you are passing to method doesn't match with method's parameter. I have used Base64 string encoding to pass file as method parameter. May it'll help you.