标签: httpclient

使用HttpClient和Web API方法[FromBody]参数发布到Web API最终为空

我正在尝试使用HttpClient POST到Web API.当我在Web API的Save方法中放置断点时,[FromBody] Product为null.这意味着我将产品发布到Web API的方式出了问题.有人可以看看下面的代码,看看我可能会出错的地方.我假设它与标题和内容类型有关.

POST从客户端存储库调用Web API,它应该通过JSON传递产品对象:

public async Task<Product> SaveProduct(Product product)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:99999/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StringContent content = new StringContent(JsonConvert.SerializeObject(product));
        // HTTP POST
        HttpResponseMessage response = await client.PostAsync("api/products/save", content);
        if (response.IsSuccessStatusCode)
        {
            string data = await response.Content.ReadAsStringAsync();
            product = JsonConvert.DeserializeObject<Product>(data);
        }
    }
    return product;
}
Run Code Online (Sandbox Code Playgroud)

Web API控制器方法:

[HttpPost]
[Route("save")]
public IActionResult Save([FromBody]Product product)
{
    if (customer == null)
    {
        return HttpBadRequest();
    }
    _manager.SaveCustomer(product);
    return CreatedAtRoute("Get", new { …
Run Code Online (Sandbox Code Playgroud)

c# asp.net httpclient asp.net-web-api

14
推荐指数
1
解决办法
6万
查看次数

.NET: file uploading to server using http

I have a running-state .php script that hits a URL and uploads a single/multiple files .csv type with a unique token sent with them (in the body AFAIK). Below is the working snippet:

PHP:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$ch = curl_init('http://demo.schooling.net/school/attendance');

$DirPath = "E:/Uploads/";

$ZKFiles=array();

if ($dh = opendir($DirPath)) 
{
    while (($file = readdir($dh)) !== false) 
    {
        if ($file == '.' || $file == '..') 
        {
            continue;
        }
        $ZKFiles[]='@'.$DirPath.$file;       
    }
    closedir($dh);
}
if(!empty($ZKFiles))
{
    // Assign POST data
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, …
Run Code Online (Sandbox Code Playgroud)

php c# asp.net-mvc webclient httpclient

14
推荐指数
1
解决办法
2993
查看次数

Logcat在每个DefaultHttpClient执行方法调用期间打印"interface name:null"

我多次联系Web服务以通过HttpGet和获取JSON字符串DefaultHttpClient.

...
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = (HttpResponse)defaultHttpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
...
Run Code Online (Sandbox Code Playgroud)

我发现LogCat是打印接口名称:null,每次都执行标签System.outHttpResponse httpResponse = (HttpResponse)defaultHttpClient.execute(httpGet);.

我正确地建立这个http连接HttpGet吗?有不同的方式吗?

如何创建此连接而不是获取接口名称:来自System.out标记的null LogCat消息?

android http-get httpresponse httpclient logcat

13
推荐指数
1
解决办法
602
查看次数

Android HttpClient不使用系统代理设置

当我创建DefaultHttpClient对象并尝试点击网页时,请求不会通过我在"设置"中指定的代理进行路由.

通过API文档,虽然Android确实有一个允许我读取系统代理设置的Proxy类,但我没有看到任何可以指定代理的地方.

有没有办法在HttpClient中使用代理设置?

proxy android httpclient

13
推荐指数
2
解决办法
2万
查看次数

Android - 具有基本身份验证的HttpClient JSON POST

我正在尝试将一个简单的JSON帖子实现到接受JSON身体基本身份验证的URL ANDROID.

我试过HttpUrlConnection但我得到了"unauthorized"我的数据发送到服务器.

我尝试的另一种方法是使用HttpClient,但现在我遇到了另一个问题.身份验证工作正常,但数据不会发送到服务器...

可以肯定的是,我在一个简单的Java项目(不是Android环境)中设置了一个小测试.

这是我POST用于服务器的代码:

DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler<String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://localhost/api/v1/purchase/");    
postMethod.setEntity(new StringEntity("{\"amount_adult\" : 1, \"object_id\" : 13}"));
postMethod.setHeader( "Content-Type", "application/json");
String authorizationString = "Basic " + Base64.encodeToString(("travelbuddy" + ":" + "travelbuddy").getBytes(), Base64.DEFAULT); //this line is diffe
postMethod.setHeader("Authorization", authorizationString);
String response = httpClient.execute(postMethod,resonseHandler);
System.out.println("response :" + response);
Run Code Online (Sandbox Code Playgroud)

Java项目中的代码非常完美.

当我在Android中尝试完全相同的代码时,我internal server error从服务器获取,这意味着尚未收到JSON数据.

我真的不明白为什么这在JAVA中工作但在Android中不起作用.

我想要实现的效果是以下命令:

curl --dump-header …
Run Code Online (Sandbox Code Playgroud)

json httpclient

13
推荐指数
2
解决办法
4万
查看次数

无法设置Content-Type标头

我在HttpClient上设置Content-Type时遇到问题.我按照这个问题:如何为HttpClient请求设置Content-Type标头? 但仍然没有运气.

String rcString = JsonConvert.SerializeObject(new RoadsmartChecks() { userguid = user_guid, coords = coordinates, radius = (radius * 100) + "" }, ROADSMART_JSON_FORMAT, JSONNET_SETTINGS);
HttpClient c = new HttpClient();
c.BaseAddress = new Uri(BASE_URL);
c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); //Keeps returning false
c.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", hash_aes);
c.DefaultRequestHeaders.TryAddWithoutValidation("Roadsmart-app", Constant.APP_ID);
c.DefaultRequestHeaders.TryAddWithoutValidation("Roadsmart-user", user_guid);
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_CHECKS + "/fetch");
req.Content = new StringContent(rcString);
await c.SendAsync(req).ContinueWith(respTask =>
{
    Debug.WriteLine("Response: {0}", respTask.Result);
});
Run Code Online (Sandbox Code Playgroud)

调试器 我也试过使用Flurl库,但在尝试添加'Content-Type'时它崩溃了.

misused header name content-type
Run Code Online (Sandbox Code Playgroud)

那么我该如何强制它以便真正添加呢?提前致谢.

c# httpclient windows-phone-8.1 flurl

13
推荐指数
1
解决办法
3万
查看次数

HttpClient GetStreamAsync和HTTP状态代码?

我希望按照json.net性能提示文档的建议使用流,但是我无法找到如何获取http状态代码而没有典型的等待HttpResponse.

是否有一种方法可以在不读取数据的情况下首先获取状态代码?所以仍然利用流?

c# stream httpclient json.net

13
推荐指数
2
解决办法
2万
查看次数

HttpClient标头与HttpRequestMessage标头

什么时候我们应该在HttpClient中的头文件中使用HttpRequestMessage对象中的头文件?

我们需要添加授权(始终更改)和少量自定义标头(始终更改)

问题

  1. 哪种方法首选?
  2. 我应该在HttpClient和HttpRequestMessage对象的基于请求的头部添加公共头(在所有请求中相同)吗?

       //HttpRequestMessage Code
        HttpRequestMessage reqmsg =new HttpRequestMessage();
        reqmsg.Headers.Authorization =new AuthenticationHeaderValue("some scheme");
        reqmsg.Headers.Add("name","value");
    
        //HttpClient Code
        HttpClient client =new HttpClient();
        client.DefaultRequestHeaders.Authorization =new AuthenticationHeaderValue("some scheme");
        client.DefaultRequestHeaders.Add("name", "value");
    
    Run Code Online (Sandbox Code Playgroud)

c# httpclient asp.net-web-api asp.net-web-api2

13
推荐指数
1
解决办法
9162
查看次数

提供了无效的请求URI.请求URI必须是绝对URI或必须设置BaseAddress

我试图使用此代码从网页获取内容:

HttpClient http = new HttpClient();
  var response = await http.GetByteArrayAsync("www.nsfund.ir/news?p_p_id=56_INSTANCE_tVzMoLp4zfGh&_56_INSTANCE_tVzMoLp4zfGh_mode=news&_56_INSTANCE_tVzMoLp4zfGh_newsId=3135919&p_p_state=maximized");
   String source = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
   source = WebUtility.HtmlDecode(source);
   HtmlDocument resultat = new HtmlDocument();
   resultat.LoadHtml(source);
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

提供了无效的请求URI.请求URI必须是绝对URI或必须设置BaseAddress.

c# http httpclient

13
推荐指数
2
解决办法
3万
查看次数

C#:ModernHttpClient,您在应用程序中引用了Portable版本 - 您需要引用平台(iOS/Android)版本

我正在使用ModernHttpClient库,我试图从httpClient的响应中获取Cookie

public static async Task<String> loginUser()
{
    var values = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("username", "*****"),
        new KeyValuePair<string, string>("password", "*****"),
    };
    NativeCookieHandler cookieHandler = new NativeCookieHandler();
    NativeMessageHandler messageHandler = new NativeMessageHandler(false, false, cookieHandler);
    var httpClient = new HttpClient(messageHandler);

    var response = await httpClient.PostAsync(RestApiPaths.LOGIN, new FormUrlEncodedContent(values));

    response.EnsureSuccessStatusCode();
    String resultString = await response.Content.ReadAsStringAsync();
    System.Diagnostics.Debug.WriteLine("resultString: " + resultString);
    IEnumerable<Cookie> responseCookies = cookieHandler.Cookies;
    Cookie mCookie = responseCookies.FirstOrDefault();
    RestApiPaths.mCookie = mCookie;
    return resultString;

}
Run Code Online (Sandbox Code Playgroud)

但是以下行给出错误:

IEnumerable<Cookie> responseCookies = cookieHandler.Cookies;
Run Code Online (Sandbox Code Playgroud)

错误:

MonoDroid] UNHANDLED EXCEPTION: …
Run Code Online (Sandbox Code Playgroud)

c# cookies android httpclient

13
推荐指数
1
解决办法
1176
查看次数